package com.shop.cereshop.app.service.order.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.shop.cereshop.app.alioss.service.UploadService;
import com.shop.cereshop.app.dao.business.CerePlatformBusinessDAO;
import com.shop.cereshop.app.dao.dl.CerePlatformUserPointDao;
import com.shop.cereshop.app.dao.order.CereShopOrderDAO;
import com.shop.cereshop.app.dao.order.DlCereOrderProductDao;
import com.shop.cereshop.app.dao.product.CereShopProductDAO;
import com.shop.cereshop.app.dao.shop.CereShopCouponRecordingDao;
import com.shop.cereshop.app.dl.logic.controller.WebSocket;
import com.shop.cereshop.app.dl.logic.domain.CereShopCommissionRecord;
import com.shop.cereshop.app.dl.logic.domian.OrderValidation;
import com.shop.cereshop.app.dl.logic.domian.ResultYf;
import com.shop.cereshop.app.dl.logic.service.CereShopCommissionRecordService;
import com.shop.cereshop.app.dl.logic.service.Impl.SendPostImpl;
import com.shop.cereshop.app.dl.logic.service.Impl.StringToListCalendar;
import com.shop.cereshop.app.dl.logic.utils.JsonUtils;
import com.shop.cereshop.app.domain.TicketInfo.CereShopTicketInfo;
import com.shop.cereshop.app.domain.shop.CereShopCouponRecording;
import com.shop.cereshop.app.page.cart.CartSku;
import com.shop.cereshop.app.page.order.*;
import com.shop.cereshop.app.page.product.ProductCoupon;
import com.shop.cereshop.app.page.settlement.Distribution;
import com.shop.cereshop.app.page.settlement.Settlement;
import com.shop.cereshop.app.page.settlement.SettlementShop;
import com.shop.cereshop.app.param.comment.CommentSaveParam;
import com.shop.cereshop.app.param.order.*;
import com.shop.cereshop.app.param.settlement.ProductSku;
import com.shop.cereshop.app.param.settlement.SettlementParam;
import com.shop.cereshop.app.param.settlement.ShopProductParam;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.service.activity.CereBuyerCouponService;
import com.shop.cereshop.app.service.after.CereAfterDileverService;
import com.shop.cereshop.app.service.after.CereOrderAfterService;
import com.shop.cereshop.app.service.buyer.CereBuyerReceiveService;
import com.shop.cereshop.app.service.buyer.CereBuyerShopCouponService;
import com.shop.cereshop.app.service.cart.CereShopCartService;
import com.shop.cereshop.app.service.dict.CerePlatformDictService;
import com.shop.cereshop.app.service.discount.CereShopDiscountDetailService;
import com.shop.cereshop.app.service.discount.CereShopDiscountService;
import com.shop.cereshop.app.service.distributor.CereDistributionOrderService;
import com.shop.cereshop.app.service.distributor.CereDistributorBuyerService;
import com.shop.cereshop.app.service.distributor.CereShopDistributorService;
import com.shop.cereshop.app.service.express.CerePlatformExpressService;
import com.shop.cereshop.app.service.express.KuaiDi100Service;
import com.shop.cereshop.app.service.express.KuaiDiNiaoService;
import com.shop.cereshop.app.service.groupwork.CereCollageOrderDetailService;
import com.shop.cereshop.app.service.groupwork.CereCollageOrderService;
import com.shop.cereshop.app.service.groupwork.CereShopGroupWorkService;
import com.shop.cereshop.app.service.log.CerePlatformLogService;
import com.shop.cereshop.app.service.logistics.CereOrderLogisticsService;
import com.shop.cereshop.app.service.notice.CereNoticeService;
import com.shop.cereshop.app.service.order.*;
import com.shop.cereshop.app.service.pay.CerePayLogService;
import com.shop.cereshop.app.service.product.CereCommentWordService;
import com.shop.cereshop.app.service.product.CereProductSkuService;
import com.shop.cereshop.app.service.product.CereShopProductService;
import com.shop.cereshop.app.service.redis.CereRedisKeyServcice;
import com.shop.cereshop.app.service.seckill.CereShopSeckillDetailService;
import com.shop.cereshop.app.service.seckill.CereShopSeckillService;
import com.shop.cereshop.app.service.sensitive.CerePlatformSensitiveService;
import com.shop.cereshop.app.service.shop.CereShopCommentService;
import com.shop.cereshop.app.service.shop.CereShopConversionService;
import com.shop.cereshop.app.weixin.service.WxPayService;
import com.shop.cereshop.commons.constant.*;
import com.shop.cereshop.commons.domain.activity.CereBuyerCoupon;
import com.shop.cereshop.commons.domain.after.CereAfterDilever;
import com.shop.cereshop.commons.domain.after.CereOrderAfter;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.domain.buyer.CereBuyerReceive;
import com.shop.cereshop.commons.domain.buyer.CereBuyerShopCoupon;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.collage.CereCollageOrder;
import com.shop.cereshop.commons.domain.collage.CereCollageOrderDetail;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.distributor.CereDistributionOrder;
import com.shop.cereshop.commons.domain.express.ShippingTrace;
import com.shop.cereshop.commons.domain.logistics.CereLogisticsCharge;
import com.shop.cereshop.commons.domain.logistics.CereOrderLogistics;
import com.shop.cereshop.commons.domain.notice.CereNotice;
import com.shop.cereshop.commons.domain.order.CereOrderParent;
import com.shop.cereshop.commons.domain.order.CereOrderProduct;
import com.shop.cereshop.commons.domain.order.CereOrderReconciliation;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.domain.pay.CerePayLog;
import com.shop.cereshop.commons.domain.product.CereCommentWord;
import com.shop.cereshop.commons.domain.product.CereProductSku;
import com.shop.cereshop.commons.domain.product.CereShopProduct;
import com.shop.cereshop.commons.domain.sensitive.CerePlatformSensitive;
import com.shop.cereshop.commons.domain.shop.CereShopComment;
import com.shop.cereshop.commons.domain.shop.CereShopConversion;
import com.shop.cereshop.commons.domain.tool.*;
import com.shop.cereshop.commons.domain.word.CerePlatformWord;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;

@Service
public class CereShopOrderServiceImpl implements CereShopOrderService {

    @Value("${Dl_Message.shopId}")
    private Long shopId;
    @Value("${points.quota}")
    private Integer quota;

    @Value("${Card.countCustomerCard}")
    private Integer countCustomerCard;

    @Value("${Detail.income}")
    private String incomeDetail;

    @Value("${Card.productNoCard}")
    private String productNoCard;

    @Autowired
    private WebSocket websocket;

    @Autowired
    private CereShopCommissionRecordService cereShopCouponRecordingsService;
    @Autowired
    private CereShopProductDAO cereShopProductDAO;
    @Autowired
    private StringRedisService stringRedisService;

    @Autowired
    private CerePlatformUserPointDao cerePlatformUserPointDao;

    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;

    @Autowired
    private CereShopCouponRecordingDao cereShopCouponRecordingDao;

    @Autowired
    private CereBuyerReceiveService buyerReceiveService;

    @Autowired
    private CereOrderLogisticsService cereOrderLogisticsService;

    @Autowired
    private CereProductSkuService cereProductSkuService;

    @Autowired
    private CereOrderParentService cereOrderParentService;

    @Autowired
    private CereDistributorBuyerService cereDistributorBuyerService;

    @Autowired
    private CereShopDistributorService cereShopDistributorService;

    @Autowired
    private CereOrderProductService cereOrderProductService;

    @Autowired
    private CereOrderProductAttributeService cereOrderProductAttributeService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private CerePlatformLogService cerePlatformLogService;

    @Autowired
    private CereDistributionOrderService cereDistributionOrderService;

    @Autowired
    private CereOrderReconciliationService cereOrderReconciliationService;

    @Autowired
    private CerePayLogService cerePayLogService;

    @Autowired
    private CerePlatformBusinessDAO cerePlatformBusinessDAO;

    @Autowired
    private CereRedisKeyServcice cereRedisKeyServcice;

    @Autowired
    private CereShopCommentService cereShopCommentService;

    @Autowired
    private CerePlatformSensitiveService cerePlatformSensitiveService;

    @Autowired
    private CereShopConversionService cereShopConversionService;

    @Autowired
    private CereShopProductService cereShopProductService;

    @Autowired
    private CereCommentWordService cereCommentWordService;

    @Autowired
    private CereBuyerCouponService cereBuyerCouponService;

    @Autowired
    private CereShopCartService cereShopCartService;

    @Autowired
    private CereAfterDileverService cereAfterDileverService;

    @Autowired
    private CereBuyerReceiveService cereBuyerReceiveService;

    @Autowired
    private CerePlatformExpressService cerePlatformExpressService;

    @Autowired
    private CerePlatformDictService cerePlatformDictService;

    @Autowired
    private KuaiDi100Service kuaiDi100Service;

    @Autowired
    private KuaiDiNiaoService kuaiDiNiaoService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private CereOrderAfterService cereOrderAfterService;

    @Autowired
    private CereBuyerShopCouponService cereBuyerShopCouponService;

    @Autowired
    private CereShopGroupWorkService cereShopGroupWorkService;

    @Autowired
    private CereCollageOrderService cereCollageOrderService;

    @Autowired
    private CereCollageOrderDetailService cereCollageOrderDetailService;

    @Autowired
    private CereShopSeckillService cereShopSeckillService;

    @Autowired
    private CereShopDiscountService cereShopDiscountService;

    @Autowired
    private CereShopSeckillDetailService cereShopSeckillDetailService;

    @Autowired
    private CereShopDiscountDetailService cereShopDiscountDetailService;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private CereNoticeService cereNoticeService;

    @Autowired
    private DlCereOrderProductService dlCereOrderProductService;

    @Autowired
    private SendPostImpl sendPost;

    @Autowired
    private DlCereOrderProductDao dlCereOrderProductDao;

    @Value("${exchangeRate}")
    private Integer exchangeRate;

    public static final String PI = "1000";

    @Override
    public Settlement getSettlement(SettlementParam param, CereBuyerUser user) throws CoBusinessException {
        Settlement settlement = new Settlement();
        if (EmptyUtils.isEmpty(param.getReceiveId())) {
            //查询默认地址
            settlement.setReceive(cereBuyerReceiveService.findlatelyReceiveByUserId(user.getBuyerUserId()));
        } else {
            settlement.setReceive(cereBuyerReceiveService.findById(param.getReceiveId()));
        }
        List<ProductCoupon> coupons = new ArrayList<>();
        if (ParamEnum.BUY_NOW.getCode().equals(param.getType())) {
            //立即购买结算查询
            buyNow(settlement, param, user, coupons);
        } else {
            //购物车结算查询
            shopCart(settlement, param, user, coupons);
        }
        List<ProductCoupon> collect = null;
        if (!EmptyUtils.isEmpty(coupons)) {
            //去除重复活动和对应金额优惠券
            collect = coupons.stream().collect(
                    Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(data -> data.getDistinct()))), ArrayList::new)
            );
            settlement.setCoupons(collect);
        }
        return settlement;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public PayUrl submit(OrderParam param, CereBuyerUser user, String ip) throws CoBusinessException, Exception {
        //商品规格id
        Long skuId = param.getShops().get(0).getSkus().get(0).getSkuId();
        //根据skuid查询类别id
        Long cid = cereShopOrderDAO.getClassifyBySKUid(skuId);
        //如果是积分商品才会进这里
        if (cid == 7) {
            //根据积分商品的skuid查询该积分商品所需积分
            Long g = cereShopOrderDAO.getPriceBySKUid(skuId);
            //根据用户id查询该用户拥有积分
            Long g2 = cereShopOrderDAO.getSumPoint(user.getBuyerUserId());
            if (g2 == null) {
                g2 = 0L;
            }
            if (g2 < g) {
//                throw new DlException(400,"积分不足, 无法兑换");
                throw new CoBusinessException(CoReturnFormat.INSUFFICIENT_POINTS);
            }
        }
        PayUrl payUrl = new PayUrl();
        String time = TimeUtils.yyMMddHHmmss();
        if (EmptyUtils.isEmpty(param.getType())) {
            //...yf（新增方法）
            CereShopTicketInfo ticketInfo = new CereShopTicketInfo();
            if (!EmptyUtils.isEmpty(param.getBookName())) {
                ticketInfo.setCustomer(param.getBookName());
            }
            if (!EmptyUtils.isEmpty(param.getBookMobile())) {
                ticketInfo.setCustomerTel(param.getBookMobile());
            }
            if (!EmptyUtils.isEmpty(param.getIdCard())) {
                ticketInfo.setCustomerCard(param.getIdCard());
            }
            if (!EmptyUtils.isEmpty(param.getMemo())) {
                ticketInfo.setMemo(param.getMemo());
            }
            if (!EmptyUtils.isEmpty(param.getTravelDate())) {
                ticketInfo.setTravelDate(param.getTravelDate());
            }
            //正常下单
            normalOrder(param, user, ip, payUrl, time, ticketInfo);
        } else if (IntegerEnum.GROUP_WORK_LAUNCH.getCode().equals(param.getType())) {
            //发起拼团
            launchOrder(param, user, ip, payUrl, time);
        } else if (IntegerEnum.GROUP_WORK_JOIN.getCode().equals(param.getType())) {
            //参与拼团
            joinOrder(param, user, ip, payUrl, time);
        } else if (IntegerEnum.SECKILL_SUBMIT.getCode().equals(param.getType())) {
            //秒杀活动下单
            seckillOrder(param, user, ip, payUrl, time);
        } else if (IntegerEnum.DISCOUNT_SUBMIT.getCode().equals(param.getType())) {
            //限时折扣活动下单
            discountOrder(param, user, ip, payUrl, time);
        }
        return payUrl;
    }

    private void discountOrder(OrderParam param, CereBuyerUser user, String ip, PayUrl payUrl, String time) throws CoBusinessException, Exception {
        CereBuyerCoupon cereBuyerCoupon = null;
        CereBuyerShopCoupon cereBuyerShopCoupon = null;
        //查询秒杀活动数据
        CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(param.getShopDiscountId());
        if (cereShopDiscount != null) {
            //定义map封装商品购买数量
            Map<Long, ProductSku> numberMap = new HashMap<>();
            param.getShops().forEach(shop -> {
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    shop.getSkus().forEach(sku -> {
                        numberMap.put(sku.getSkuId(), sku);
                    });
                }
            });
            Map<Long, CartSku> map = new HashMap<>();
            if (!EmptyUtils.isEmpty(param.getShops())) {
                AtomicBoolean flag = new AtomicBoolean(false);
                //定义运费
                BigDecimal logisticPrice = new BigDecimal(0);
                //定义批量更新限量数据
                List<CereShopDiscountDetail> discountDetails = new ArrayList<>();
                for (OrderProductParam shop : param.getShops()) {
                    if (!EmptyUtils.isEmpty(shop.getDistribution())) {
                        //计算总得运费
                        logisticPrice = logisticPrice.add(shop.getDistribution().getDistributionPrice());
                    }
                    if (!EmptyUtils.isEmpty(shop.getSkus())) {
                        //查询当前店铺所有购买商品的库存数据
                        List<CartSku> productSkus = cereProductSkuService.findDiscountStockNumberBySkus(shop.getSkus(), cereShopDiscount.getShopDiscountId());
                        if (!EmptyUtils.isEmpty(productSkus)) {
                            for (CartSku sku : productSkus) {
                                //校验限量和限购
                                checkDiscountActivity(cereShopDiscount, numberMap.get(sku.getSkuId()).getNumber(), sku, discountDetails);
                                //设置购买数量
                                sku.setNumber(numberMap.get(sku.getSkuId()).getNumber());
                                //设置选中状态
                                sku.setSelected(numberMap.get(sku.getSkuId()).getSelected());
                                //设置店铺id
                                sku.setShopId(shop.getShopId());
                                map.put(sku.getSkuId(), sku);
                            }
                        }
                        shop.getSkus().forEach(sku -> {
                            if (IntegerEnum.NO.getCode().equals(map.get(sku.getSkuId()).getIfOversold())) {
                                //如果不允许超卖,校验redis中商品库存
                                int stockNumber = 0;
                                if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                    stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                                } else {
                                    stockNumber = map.get(sku.getSkuId()).getStockNumber();
                                }
                                if (sku.getNumber() > stockNumber) {
                                    flag.set(true);
                                }
                            }
                        });
                    }
                }
                if (flag.get()) {
                    throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
                }
                //计算订单总金额
                BigDecimal orderPrice = setOrderPrice(map, numberMap);
                //查询平台优惠券数据
                cereBuyerCoupon = cereBuyerCouponService.findByCouponId(param.getCouponId(), user.getBuyerUserId());
                //定义店铺优惠券map
                Map<Long, CereBuyerShopCoupon> discountMap = new HashMap<>();
                //设置优惠金额
                param.setDiscountPrice(setDiscountPrice(cereBuyerCoupon, param, map, numberMap, discountMap));
                //计算订单实付金额=订单总金额-优惠+运费
                if (!EmptyUtils.isEmpty(logisticPrice)) {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()).add(logisticPrice));
                } else {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()));
                }
                //新增父订单数据
                CereOrderParent parent = new CereOrderParent();
                parent.setCreateTime(time);
                parent.setLogisticsPrice(logisticPrice);
                //订单总价
                parent.setOrderPrice(orderPrice);
                parent.setPrice(param.getPrice());
                parent.setParentFormid(RandomStringUtil.getRandomCode(15, 0));
                cereOrderParentService.insert(parent);
                payUrl.setMoney(parent.getPrice());
                payUrl.setOrderId(parent.getParentId());
                if (EmptyUtils.isEmptyBigdecimal(payUrl.getMoney())) {
                    //如果金额为0,提示
                    throw new CoBusinessException(CoReturnFormat.PAY_MONEY_NOT_ZERO);
                }
                //生成支付二维码
                generatePayUrl(param, user.getWechatOpenId(), parent.getParentFormid(), payUrl.getMoney(), ip, payUrl);

                //遍历店铺数据,新增订单
                addDiscountOrder(parent.getParentId(), param, user, time, map, cereBuyerCoupon, discountMap, discountDetails);
            }
        }
    }

    private void seckillOrder(OrderParam param, CereBuyerUser user, String ip, PayUrl payUrl, String time) throws CoBusinessException, Exception {
        CereBuyerCoupon cereBuyerCoupon = null;
        CereBuyerShopCoupon cereBuyerShopCoupon = null;
        //查询秒杀活动数据
        CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(param.getShopSeckillId());
        if (cereShopSeckill != null) {
            //定义map封装商品购买数量
            Map<Long, ProductSku> numberMap = new HashMap<>();
            param.getShops().forEach(shop -> {
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    shop.getSkus().forEach(sku -> {
                        numberMap.put(sku.getSkuId(), sku);
                    });
                }
            });
            Map<Long, CartSku> map = new HashMap<>();
            if (!EmptyUtils.isEmpty(param.getShops())) {
                AtomicBoolean flag = new AtomicBoolean(false);
                //定义运费
                BigDecimal logisticPrice = new BigDecimal(0);
                //定义批量更新限量库存数据
                List<CereShopSeckillDetail> seckillDetails = new ArrayList<>();
                for (OrderProductParam shop : param.getShops()) {
                    if (!EmptyUtils.isEmpty(shop.getDistribution())) {
                        //计算总得运费
                        logisticPrice = logisticPrice.add(shop.getDistribution().getDistributionPrice());
                    }
                    if (!EmptyUtils.isEmpty(shop.getSkus())) {
                        //查询当前店铺所有购买商品的库存数据
                        List<CartSku> productSkus = cereProductSkuService.findSeckillStockNumberBySkus(shop.getSkus(), cereShopSeckill.getShopSeckillId());
                        if (!EmptyUtils.isEmpty(productSkus)) {
                            for (CartSku sku : productSkus) {
                                //校验是否限量和限购
                                checkSeckillActivity(cereShopSeckill, numberMap.get(sku.getSkuId()).getNumber(), sku, seckillDetails);
                                //设置购买数量
                                sku.setNumber(numberMap.get(sku.getSkuId()).getNumber());
                                //设置选中状态
                                sku.setSelected(numberMap.get(sku.getSkuId()).getSelected());
                                //设置店铺id
                                sku.setShopId(shop.getShopId());
                                map.put(sku.getSkuId(), sku);
                            }
                        }
                        shop.getSkus().forEach(sku -> {
                            if (IntegerEnum.NO.getCode().equals(map.get(sku.getSkuId()).getIfOversold())) {
                                //如果不允许超卖,校验redis中商品库存
                                int stockNumber = 0;
                                if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                    stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                                } else {
                                    stockNumber = map.get(sku.getSkuId()).getStockNumber();
                                }
                                if (sku.getNumber() > stockNumber) {
                                    flag.set(true);
                                }
                            }
                        });
                    }
                }
                if (flag.get()) {
                    throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
                }
                //计算订单总金额
                BigDecimal orderPrice = setOrderPrice(map, numberMap);
                //查询平台优惠券数据
                cereBuyerCoupon = cereBuyerCouponService.findByCouponId(param.getCouponId(), user.getBuyerUserId());
                //定义店铺优惠券map
                Map<Long, CereBuyerShopCoupon> discountMap = new HashMap<>();
                //设置优惠金额
                param.setDiscountPrice(setDiscountPrice(cereBuyerCoupon, param, map, numberMap, discountMap));
                //计算订单实付金额=订单总金额-优惠+运费
                if (!EmptyUtils.isEmpty(logisticPrice)) {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()).add(logisticPrice));
                } else {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()));
                }
                //新增父订单数据
                CereOrderParent parent = new CereOrderParent();
                parent.setCreateTime(time);
                parent.setLogisticsPrice(logisticPrice);
                //订单总价
                parent.setOrderPrice(orderPrice);
                parent.setPrice(param.getPrice());
                parent.setParentFormid(RandomStringUtil.getRandomCode(15, 0));
                cereOrderParentService.insert(parent);
                payUrl.setMoney(parent.getPrice());
                payUrl.setOrderId(parent.getParentId());
                if (EmptyUtils.isEmptyBigdecimal(payUrl.getMoney())) {
                    //如果金额为0,提示
                    throw new CoBusinessException(CoReturnFormat.PAY_MONEY_NOT_ZERO);
                }
                //生成支付二维码
                generatePayUrl(param, user.getWechatOpenId(), parent.getParentFormid(), payUrl.getMoney(), ip, payUrl);

                //遍历店铺数据,新增订单
                addSeckillOrder(parent.getParentId(), param, user, time, map, cereBuyerCoupon, discountMap, seckillDetails);
            }
        }
    }

    private void joinOrder(OrderParam param, CereBuyerUser user, String ip, PayUrl payUrl, String time) throws CoBusinessException, Exception {
        CereBuyerCoupon cereBuyerCoupon = null;
        CereBuyerShopCoupon cereBuyerShopCoupon = null;
        //发起拼团提交订单业务处理
        //查询拼团活动数据
        CereShopGroupWork cereShopGroupWork = cereShopGroupWorkService.findById(param.getShopGroupWorkId());
        if (cereShopGroupWork != null) {
            //定义map封装商品购买数量
            Map<Long, ProductSku> numberMap = new HashMap<>();
            param.getShops().forEach(shop -> {
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    shop.getSkus().forEach(sku -> {
                        numberMap.put(sku.getSkuId(), sku);
                    });
                }
            });
            Map<Long, CartSku> map = new HashMap<>();
            if (!EmptyUtils.isEmpty(param.getShops())) {
                AtomicBoolean flag = new AtomicBoolean(false);
                BigDecimal logisticPrice = new BigDecimal(0);
                for (OrderProductParam shop : param.getShops()) {
                    if (!EmptyUtils.isEmpty(shop.getDistribution())) {
                        logisticPrice = logisticPrice.add(shop.getDistribution().getDistributionPrice());
                    }
                    if (!EmptyUtils.isEmpty(shop.getSkus())) {
                        //查询当前店铺所有购买商品的库存数据
                        List<CartSku> productSkus = cereProductSkuService.findGroupWorkStockNumberBySkus(shop.getSkus(), cereShopGroupWork.getShopGroupWorkId());
                        if (!EmptyUtils.isEmpty(productSkus)) {
                            productSkus.forEach(sku -> {
                                //设置购买数量
                                sku.setNumber(numberMap.get(sku.getSkuId()).getNumber());
                                //设置选中状态
                                sku.setSelected(numberMap.get(sku.getSkuId()).getSelected());
                                //设置店铺id
                                sku.setShopId(shop.getShopId());
                                map.put(sku.getSkuId(), sku);
                            });
                        }
                        shop.getSkus().forEach(sku -> {
                            if (IntegerEnum.NO.getCode().equals(map.get(sku.getSkuId()).getIfOversold())) {
                                //如果不允许超卖,校验redis中商品库存
                                int stockNumber = 0;
                                if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                    stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                                } else {
                                    stockNumber = map.get(sku.getSkuId()).getStockNumber();
                                }
                                if (sku.getNumber() > stockNumber) {
                                    flag.set(true);
                                }
                            }
                        });
                    }
                }
                if (flag.get()) {
                    throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
                }
                //计算订单总金额
                BigDecimal orderPrice = setOrderPrice(map, numberMap);
                //查询平台优惠券数据
                cereBuyerCoupon = cereBuyerCouponService.findByCouponId(param.getCouponId(), user.getBuyerUserId());
                //定义店铺优惠券map
                Map<Long, CereBuyerShopCoupon> discountMap = new HashMap<>();
                //设置优惠金额
                param.setDiscountPrice(setDiscountPrice(cereBuyerCoupon, param, map, numberMap, discountMap));
                //计算订单实付金额=订单总金额-优惠+运费
                if (!EmptyUtils.isEmpty(logisticPrice)) {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()).add(logisticPrice));
                } else {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()));
                }
                //新增父订单数据
                CereOrderParent parent = new CereOrderParent();
                parent.setCreateTime(time);
                parent.setLogisticsPrice(logisticPrice);
                parent.setOrderPrice(orderPrice);
                parent.setPrice(param.getPrice());
                parent.setParentFormid(RandomStringUtil.getRandomCode(15, 0));
                cereOrderParentService.insert(parent);
                payUrl.setMoney(parent.getPrice());
                payUrl.setOrderId(parent.getParentId());
                if (EmptyUtils.isEmptyBigdecimal(payUrl.getMoney())) {
                    //如果金额为0,提示
                    throw new CoBusinessException(CoReturnFormat.PAY_MONEY_NOT_ZERO);
                }
                //生成支付二维码
                generatePayUrl(param, user.getWechatOpenId(), parent.getParentFormid(), parent.getOrderPrice(), ip, payUrl);

                //遍历店铺数据,新增订单
                addlaunchOrder(parent.getParentId(), param, user, time, map, cereBuyerCoupon, discountMap, cereShopGroupWork, payUrl);
            }
        }
    }

    private void launchOrder(OrderParam param, CereBuyerUser user, String ip, PayUrl payUrl, String time) throws CoBusinessException, Exception {
        CereBuyerCoupon cereBuyerCoupon = null;
        CereBuyerShopCoupon cereBuyerShopCoupon = null;
        //发起拼团提交订单业务处理
        //查询拼团活动数据
        CereShopGroupWork cereShopGroupWork = cereShopGroupWorkService.findById(param.getShopGroupWorkId());
        if (cereShopGroupWork != null) {
            //定义map封装商品购买数量
            Map<Long, ProductSku> numberMap = new HashMap<>();
            param.getShops().forEach(shop -> {
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    shop.getSkus().forEach(sku -> {
                        numberMap.put(sku.getSkuId(), sku);
                    });
                }
            });
            Map<Long, CartSku> map = new HashMap<>();
            if (!EmptyUtils.isEmpty(param.getShops())) {
                AtomicBoolean flag = new AtomicBoolean(false);
                //定义运费
                BigDecimal logisticPrice = new BigDecimal(0);
                for (OrderProductParam shop : param.getShops()) {
                    if (!EmptyUtils.isEmpty(shop.getDistribution())) {
                        //计算总得运费
                        logisticPrice = logisticPrice.add(shop.getDistribution().getDistributionPrice());
                    }
                    if (!EmptyUtils.isEmpty(shop.getSkus())) {
                        //查询当前店铺所有购买商品的库存数据
                        List<CartSku> productSkus = cereProductSkuService.findGroupWorkStockNumberBySkus(shop.getSkus(), cereShopGroupWork.getShopGroupWorkId());
                        if (!EmptyUtils.isEmpty(productSkus)) {
                            productSkus.forEach(sku -> {
                                //设置购买数量
                                sku.setNumber(numberMap.get(sku.getSkuId()).getNumber());
                                //设置选中状态
                                sku.setSelected(numberMap.get(sku.getSkuId()).getSelected());
                                //设置店铺id
                                sku.setShopId(shop.getShopId());
                                map.put(sku.getSkuId(), sku);
                            });
                        }
                        shop.getSkus().forEach(sku -> {
                            if (IntegerEnum.NO.getCode().equals(map.get(sku.getSkuId()).getIfOversold())) {
                                //如果不允许超卖,校验redis中商品库存
                                int stockNumber = 0;
                                if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                    stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                                } else {
                                    stockNumber = map.get(sku.getSkuId()).getStockNumber();
                                }
                                if (sku.getNumber() > stockNumber) {
                                    flag.set(true);
                                }
                            }
                        });
                    }
                }
                if (flag.get()) {
                    throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
                }
                //计算订单总金额
                BigDecimal orderPrice = setOrderPrice(map, numberMap);
                //查询平台优惠券数据
                cereBuyerCoupon = cereBuyerCouponService.findByCouponId(param.getCouponId(), user.getBuyerUserId());
                //定义店铺优惠券map
                Map<Long, CereBuyerShopCoupon> discountMap = new HashMap<>();
                //设置优惠金额
                param.setDiscountPrice(setDiscountPrice(cereBuyerCoupon, param, map, numberMap, discountMap));
                //计算订单实付金额=订单总金额-优惠+运费
                if (!EmptyUtils.isEmpty(logisticPrice)) {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()).add(logisticPrice));
                } else {
                    param.setPrice(orderPrice.subtract(param.getDiscountPrice()));
                }
                //新增父订单数据
                CereOrderParent parent = new CereOrderParent();
                parent.setCreateTime(time);
                parent.setLogisticsPrice(logisticPrice);
                //订单总价
                parent.setOrderPrice(orderPrice);
                parent.setPrice(param.getPrice());
                parent.setParentFormid(RandomStringUtil.getRandomCode(15, 0));
                cereOrderParentService.insert(parent);
                payUrl.setMoney(parent.getPrice());
                payUrl.setOrderId(parent.getParentId());
                if (EmptyUtils.isEmptyBigdecimal(payUrl.getMoney())) {
                    //如果金额为0,提示
                    throw new CoBusinessException(CoReturnFormat.PAY_MONEY_NOT_ZERO);
                }
                //生成支付二维码
                generatePayUrl(param, user.getWechatOpenId(), parent.getParentFormid(), payUrl.getMoney(), ip, payUrl);

                //遍历店铺数据,新增订单
                addlaunchOrder(parent.getParentId(), param, user, time, map, cereBuyerCoupon, discountMap, cereShopGroupWork, payUrl);
            }
        }
    }

    private void addlaunchOrder(Long parentId, OrderParam param, CereBuyerUser user, String time, Map<Long, CartSku> map,
                                CereBuyerCoupon buyerCoupon, Map<Long, CereBuyerShopCoupon> discountMap,
                                CereShopGroupWork cereShopGroupWork, PayUrl payUrl) throws CoBusinessException, Exception {
        //遍历店铺
        List<CartSku> carts = new ArrayList<>();
        List<CartSku> skus = null;
        if (!EmptyUtils.isEmpty(map)) {
            //拿到所有商品数据
            skus = map.keySet().stream().map(key -> map.get(key)).collect(Collectors.toList());
        }
        //查询所有规格属性数据
        List<OrderProductAttribute> attributes = cereOrderProductAttributeService.findBySkus(skus);
        //查询收货地址数据
        CereBuyerReceive receive = cereBuyerReceiveService.findById(param.getReceiveId());
        if (receive != null) {
            for (OrderProductParam shop : param.getShops()) {
                //封装子订单数据
                CereShopOrder order = new CereShopOrder();
                order.setShopId(shop.getShopId());
                order.setParentId(parentId);
                order.setBuyerUserId(user.getBuyerUserId());
                order.setCreateTime(time);
                order.setUpdateTime(time);
                order.setCouponId(param.getCouponId());
                order.setReceiveName(receive.getReceiveName());
                order.setReceivePhone(receive.getReceivePhone());
                order.setReceiveAdress(receive.getReceiveAdress());
                order.setAddress(receive.getAddress());
                order.setCustomerName(user.getWechatName());
                order.setCustomerPhone(user.getPhone());
                order.setLogisticsPrice(shop.getDistribution().getDistributionPrice());
                order.setLogisticsId(shop.getDistribution().getLogisticsId());
                order.setState(IntegerEnum.ORDER_STAY_PAY.getCode());
                order.setOrderFormid(RandomStringUtil.getRandomCode(15, 0));
                //定义订单优惠券金额（平台优惠金额/店铺总数+店铺优惠金额）
                BigDecimal discountPrice = new BigDecimal(0);
                if (buyerCoupon != null) {
                    discountPrice = buyerCoupon.getReduceMoney().divide(
                            new BigDecimal(param.getShops().size()), 2, BigDecimal.ROUND_HALF_UP);
                    //更新平台优惠券状态为已使用
                    buyerCoupon.setUpdateTime(time);
                    buyerCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                    cereBuyerCouponService.updateState(buyerCoupon);
                    //删除redis延时任务
                    stringRedisService.delete(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                    //删除redis记录数据
                    cereRedisKeyServcice.deleteByKey(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                }
                //计算订单优惠金额
                if (!EmptyUtils.isEmpty(shop.getId()) && !EmptyUtils.isEmpty(discountMap)) {
                    order.setId(shop.getId());
                    if (!EmptyUtils.isEmpty(discountMap.get(shop.getId()))) {
                        CereBuyerShopCoupon cereBuyerShopCoupon = discountMap.get(shop.getId());
                        //更新店铺优惠券状态为已使用
                        cereBuyerShopCoupon.setUpdateTime(time);
                        cereBuyerShopCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                        cereBuyerShopCouponService.updateState(cereBuyerShopCoupon);
                        //删除redis延时任务
                        stringRedisService.delete(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        cereRedisKeyServcice.deleteByKey(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        order.setShopOperateId(cereBuyerShopCoupon.getShopOperateId());
                        if (!EmptyUtils.isEmptyBigdecimal(discountPrice)) {
                            discountPrice = discountPrice.add(cereBuyerShopCoupon.getReduceMoney());
                        } else {
                            discountPrice = cereBuyerShopCoupon.getReduceMoney();
                        }
                    }
                }
                order.setDiscountPrice(discountPrice);
                if (!EmptyUtils.isEmpty(skus)) {
                    //定义店铺商品总金额字段
                    final BigDecimal[] total = {new BigDecimal(0)};
                    //设置规格数量
                    skus.forEach(sku -> {
                        if (sku.getShopId().equals(shop.getShopId())) {
                            total[0] = total[0].add(sku.getPrice().multiply(
                                    new BigDecimal(sku.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    //订单总金额=店铺商品总金额+运费
                    order.setOrderPrice(total[0].add(order.getLogisticsPrice()));
                    //订单支付金额=订单总金额-优惠
                    order.setPrice(order.getOrderPrice().subtract(order.getDiscountPrice()));
                    order.setPaymentState(IntegerEnum.ORDER_PAY_STAY.getCode());
                    order.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
                    order.setRemark(param.getRemark());
                    order.setBuyerUserId(user.getBuyerUserId());
                    order.setShopGroupWorkId(param.getShopGroupWorkId());
                    //插入订单数据
                    cereShopOrderDAO.insert(order);
                    //新增订单商品数据
                    addOrderProduct(skus, order.getOrderId(), shop.getShopId(), map, carts, attributes);
                    Long collageId = param.getCollageId();
                    if (EmptyUtils.isEmpty(param.getCollageId())) {
                        //生成拼单数据
                        CereCollageOrder cereCollageOrder = new CereCollageOrder();
                        cereCollageOrder.setBuyerUserId(user.getBuyerUserId());
                        cereCollageOrder.setCreateTime(time);
                        cereCollageOrder.setShopGroupWorkId(param.getShopGroupWorkId());
                        cereCollageOrder.setSurplusNumber(cereShopGroupWork.getPerson());
                        cereCollageOrder.setState(IntegerEnum.COLLAGE_STATE_STAY.getCode());
                        cereCollageOrderService.insert(cereCollageOrder);
                        collageId = cereCollageOrder.getCollageId();
                        param.setCollageId(cereCollageOrder.getCollageId());
                        //设置该拼单截止时间
                        String end = TimeUtils.getMoreHourAfter(time, cereShopGroupWork.getEffectiveTime());
                        //新增redis延时任务处理拼团失败
                        stringRedisService.set(StringEnum.COLLAGE_ERROR.getCode() + "-" + cereCollageOrder.getCollageId(), 1,
                                TimeUtils.getCountDownByTime(time, end));
                        //新增延时记录
                        cereRedisKeyServcice.add(StringEnum.COLLAGE_ERROR.getCode() + "-" + cereCollageOrder.getCollageId(), end);
                    }
                    //生成拼单明细数据
                    CereCollageOrderDetail detail = new CereCollageOrderDetail();
                    detail.setCollageId(collageId);
                    detail.setOrderId(order.getOrderId());
                    detail.setState(IntegerEnum.YES.getCode());
                    cereCollageOrderDetailService.insert(detail);
                    payUrl.setCollageId(collageId);
                }
            }
            //批量更新库存数量
            cereProductSkuService.updateBatch(skus);
            //插入规格属性数据
            if (!EmptyUtils.isEmpty(attributes)) {
                cereOrderProductAttributeService.insertBatch(attributes);
            }
        }
    }

    private void addSeckillOrder(Long parentId, OrderParam param, CereBuyerUser user, String time, Map<Long, CartSku> map,
                                 CereBuyerCoupon buyerCoupon, Map<Long, CereBuyerShopCoupon> discountMap,
                                 List<CereShopSeckillDetail> seckillDetails) throws CoBusinessException, Exception {
        //遍历店铺
        List<CartSku> carts = new ArrayList<>();
        List<CartSku> skus = null;
        if (!EmptyUtils.isEmpty(map)) {
            //拿到所有商品数据
            skus = map.keySet().stream().map(key -> map.get(key)).collect(Collectors.toList());
        }
        //查询所有规格属性数据
        List<OrderProductAttribute> attributes = cereOrderProductAttributeService.findBySkus(skus);
        //查询收货地址数据
        CereBuyerReceive receive = cereBuyerReceiveService.findById(param.getReceiveId());
        if (receive != null) {
            for (OrderProductParam shop : param.getShops()) {
                //封装子订单数据
                CereShopOrder order = new CereShopOrder();
                order.setShopId(shop.getShopId());
                order.setParentId(parentId);
                order.setBuyerUserId(user.getBuyerUserId());
                order.setCreateTime(time);
                order.setUpdateTime(time);
                order.setShopSeckillId(param.getShopSeckillId());
                order.setCouponId(param.getCouponId());
                order.setReceiveName(receive.getReceiveName());
                order.setReceivePhone(receive.getReceivePhone());
                order.setReceiveAdress(receive.getReceiveAdress());
                order.setAddress(receive.getAddress());
                order.setCustomerName(user.getWechatName());
                order.setCustomerPhone(user.getPhone());
                order.setLogisticsPrice(shop.getDistribution().getDistributionPrice());
                order.setLogisticsId(shop.getDistribution().getLogisticsId());
                order.setState(IntegerEnum.ORDER_STAY_PAY.getCode());
                order.setOrderFormid(RandomStringUtil.getRandomCode(15, 0));
                //定义订单优惠券金额（平台优惠金额/店铺总数+店铺优惠金额）
                BigDecimal discountPrice = new BigDecimal(0);
                if (buyerCoupon != null) {
                    discountPrice = buyerCoupon.getReduceMoney().divide(
                            new BigDecimal(param.getShops().size()), 2, BigDecimal.ROUND_HALF_UP);
                    //更新平台优惠券状态为已使用
                    buyerCoupon.setUpdateTime(time);
                    buyerCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                    cereBuyerCouponService.updateState(buyerCoupon);
                    //删除redis延时任务
                    stringRedisService.delete(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                    //删除redis记录数据
                    cereRedisKeyServcice.deleteByKey(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                }
                //计算订单优惠金额
                if (!EmptyUtils.isEmpty(shop.getId()) && !EmptyUtils.isEmpty(discountMap)) {
                    order.setId(shop.getId());
                    if (!EmptyUtils.isEmpty(discountMap.get(shop.getId()))) {
                        CereBuyerShopCoupon cereBuyerShopCoupon = discountMap.get(shop.getId());
                        //更新店铺优惠券状态为已使用
                        cereBuyerShopCoupon.setUpdateTime(time);
                        cereBuyerShopCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                        cereBuyerShopCouponService.updateState(cereBuyerShopCoupon);
                        //删除redis延时任务
                        stringRedisService.delete(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        cereRedisKeyServcice.deleteByKey(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        order.setShopOperateId(cereBuyerShopCoupon.getShopOperateId());
                        if (!EmptyUtils.isEmptyBigdecimal(discountPrice)) {
                            discountPrice = discountPrice.add(cereBuyerShopCoupon.getReduceMoney());
                        } else {
                            discountPrice = cereBuyerShopCoupon.getReduceMoney();
                        }
                    }
                }
                order.setDiscountPrice(discountPrice);
                if (!EmptyUtils.isEmpty(skus)) {
                    //定义店铺商品总金额字段
                    final BigDecimal[] total = {new BigDecimal(0)};
                    //设置规格数量
                    skus.forEach(sku -> {
                        if (sku.getShopId().equals(shop.getShopId())) {
                            total[0] = total[0].add(sku.getPrice().multiply(
                                    new BigDecimal(sku.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    //订单总金额=店铺商品总金额+运费
                    order.setOrderPrice(total[0].add(order.getLogisticsPrice()));
                    //订单支付金额=订单总金额-优惠
                    order.setPrice(order.getOrderPrice().subtract(order.getDiscountPrice()));
                    order.setPaymentState(IntegerEnum.ORDER_PAY_STAY.getCode());
                    order.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
                    order.setRemark(param.getRemark());
                    order.setBuyerUserId(user.getBuyerUserId());
                    order.setShopGroupWorkId(param.getShopGroupWorkId());
                    //插入订单数据
                    cereShopOrderDAO.insert(order);
                    //新增订单商品数据
                    addOrderProduct(skus, order.getOrderId(), shop.getShopId(), map, carts, attributes);
                    //设置30分钟延时自动取消订单,并且释放库存
                    stringRedisService.set(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), param.getShops(), 30 * 60 * 1000);
                    //新增延时任务记录
                    cereRedisKeyServcice.add(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), TimeUtils.getMinuteAfter(30));
                }
            }
            //批量更新库存数量
            cereProductSkuService.updateBatch(skus);
            if (!EmptyUtils.isEmpty(seckillDetails)) {
                //设置缓存中限量库存数据
                seckillDetails.forEach(detail -> {
                    stringRedisService.set("秒杀活动商品仅剩件数" + detail.getShopSeckillId() + detail.getSkuId(), detail.getNumber());
                });
                //批量更新限量库存数量
                cereShopSeckillDetailService.updateBatch(seckillDetails);
            }
            //插入规格属性数据
            if (!EmptyUtils.isEmpty(attributes)) {
                cereOrderProductAttributeService.insertBatch(attributes);
            }
        }
    }

    private void addDiscountOrder(Long parentId, OrderParam param, CereBuyerUser user, String time, Map<Long, CartSku> map,
                                  CereBuyerCoupon buyerCoupon, Map<Long, CereBuyerShopCoupon> discountMap,
                                  List<CereShopDiscountDetail> discountDetails) throws CoBusinessException, Exception {
        //遍历店铺
        List<CartSku> carts = new ArrayList<>();
        List<CartSku> skus = null;
        if (!EmptyUtils.isEmpty(map)) {
            //拿到所有商品数据
            skus = map.keySet().stream().map(key -> map.get(key)).collect(Collectors.toList());
        }
        //查询所有规格属性数据
        List<OrderProductAttribute> attributes = cereOrderProductAttributeService.findBySkus(skus);
        //查询收货地址数据
        CereBuyerReceive receive = cereBuyerReceiveService.findById(param.getReceiveId());
        if (receive != null) {
            for (OrderProductParam shop : param.getShops()) {
                //封装子订单数据
                CereShopOrder order = new CereShopOrder();
                order.setShopId(shop.getShopId());
                order.setParentId(parentId);
                order.setBuyerUserId(user.getBuyerUserId());
                order.setCreateTime(time);
                order.setUpdateTime(time);
                order.setShopDiscountId(param.getShopDiscountId());
                order.setCouponId(param.getCouponId());
                order.setReceiveName(receive.getReceiveName());
                order.setReceivePhone(receive.getReceivePhone());
                order.setReceiveAdress(receive.getReceiveAdress());
                order.setAddress(receive.getAddress());
                order.setCustomerName(user.getWechatName());
                order.setCustomerPhone(param.getBookMobile());
                order.setLogisticsPrice(shop.getDistribution().getDistributionPrice());
                order.setLogisticsId(shop.getDistribution().getLogisticsId());
                order.setState(IntegerEnum.ORDER_STAY_PAY.getCode());
                order.setOrderFormid(RandomStringUtil.getRandomCode(15, 0));
                //定义订单优惠券金额（平台优惠金额/店铺总数+店铺优惠金额）
                BigDecimal discountPrice = new BigDecimal(0);
                if (buyerCoupon != null) {
                    discountPrice = buyerCoupon.getReduceMoney().divide(
                            new BigDecimal(param.getShops().size()), 2, BigDecimal.ROUND_HALF_UP);
                    //更新平台优惠券状态为已使用
                    buyerCoupon.setUpdateTime(time);
                    buyerCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                    cereBuyerCouponService.updateState(buyerCoupon);
                    //删除redis延时任务
                    stringRedisService.delete(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                    //删除redis记录数据
                    cereRedisKeyServcice.deleteByKey(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                }
                //计算订单优惠金额
                if (!EmptyUtils.isEmpty(shop.getId()) && !EmptyUtils.isEmpty(discountMap)) {
                    order.setId(shop.getId());
                    if (!EmptyUtils.isEmpty(discountMap.get(shop.getId()))) {
                        CereBuyerShopCoupon cereBuyerShopCoupon = discountMap.get(shop.getId());
                        //更新店铺优惠券状态为已使用
                        cereBuyerShopCoupon.setUpdateTime(time);
                        cereBuyerShopCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                        cereBuyerShopCouponService.updateState(cereBuyerShopCoupon);
                        //删除redis延时任务
                        stringRedisService.delete(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        cereRedisKeyServcice.deleteByKey(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        order.setShopOperateId(cereBuyerShopCoupon.getShopOperateId());
                        if (!EmptyUtils.isEmptyBigdecimal(discountPrice)) {
                            discountPrice = discountPrice.add(cereBuyerShopCoupon.getReduceMoney());
                        } else {
                            discountPrice = cereBuyerShopCoupon.getReduceMoney();
                        }
                    }
                }
                order.setDiscountPrice(discountPrice);
                if (!EmptyUtils.isEmpty(skus)) {
                    //定义店铺商品总金额字段
                    final BigDecimal[] total = {new BigDecimal(0)};
                    //设置规格数量
                    skus.forEach(sku -> {
                        if (sku.getShopId().equals(shop.getShopId())) {
                            total[0] = total[0].add(sku.getPrice().multiply(
                                    new BigDecimal(sku.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    //订单总金额=店铺商品总金额+运费
                    order.setOrderPrice(total[0].add(order.getLogisticsPrice()));
                    //订单支付金额=订单总金额-优惠
                    order.setPrice(order.getOrderPrice().subtract(order.getDiscountPrice()));
                    order.setPaymentState(IntegerEnum.ORDER_PAY_STAY.getCode());
                    order.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
                    order.setRemark(param.getRemark());
                    order.setBuyerUserId(user.getBuyerUserId());
                    order.setShopGroupWorkId(param.getShopGroupWorkId());
                    //插入订单数据
                    cereShopOrderDAO.insert(order);
                    //新增订单商品数据
                    addOrderProduct(skus, order.getOrderId(), shop.getShopId(), map, carts, attributes);
                    //设置30分钟延时自动取消订单,并且释放库存
                    stringRedisService.set(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), param.getShops(), 30 * 60 * 1000);
                    //新增延时任务记录
                    cereRedisKeyServcice.add(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), TimeUtils.getMinuteAfter(30));
                }
            }
            //批量更新库存数量
            cereProductSkuService.updateBatch(skus);
            if (!EmptyUtils.isEmpty(discountDetails)) {
                //设置缓存中限量库存数据
                discountDetails.forEach(detail -> {
                    stringRedisService.set("限时折扣活动商品仅剩件数" + detail.getShopDiscountId() + detail.getSkuId(), detail.getNumber());
                });
                //批量更新限量库存数据
                cereShopDiscountDetailService.updateBatch(discountDetails);
            }
            //插入规格属性数据
            if (!EmptyUtils.isEmpty(attributes)) {
                cereOrderProductAttributeService.insertBatch(attributes);
            }
        }
    }

    private void normalOrder(OrderParam param, CereBuyerUser user, String ip, PayUrl payUrl, String time, CereShopTicketInfo ticketInfo) throws CoBusinessException, Exception {
        Map<Long, CartSku> map = new HashMap<>();
        if (!EmptyUtils.isEmpty(param.getShops())) {
            //定义map封装商品购买数量
            Map<Long, ProductSku> numberMap = new HashMap<>();
            param.getShops().forEach(shop -> {
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    shop.getSkus().forEach(sku -> {
                        numberMap.put(sku.getSkuId(), sku);
                    });
                }
            });
            //校验商品库存
            AtomicBoolean flag = new AtomicBoolean(false);
            //定义运费
            BigDecimal logisticPrice = new BigDecimal(0);
            for (OrderProductParam shop : param.getShops()) {
                if (!EmptyUtils.isEmpty(shop.getDistribution())) {
                    //计算总得运费
                    logisticPrice = logisticPrice.add(shop.getDistribution().getDistributionPrice());
                }
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    //查询当前店铺所有购买商品的库存数据
                    List<CartSku> productSkus = cereProductSkuService.findStockNumberBySkus(shop.getSkus());
                    if (!EmptyUtils.isEmpty(productSkus)) {
                        productSkus.forEach(sku -> {
                            //设置购买数量
                            sku.setNumber(numberMap.get(sku.getSkuId()).getNumber());
                            //设置选中状态
                            sku.setSelected(numberMap.get(sku.getSkuId()).getSelected());
                            //设置店铺id
                            sku.setShopId(shop.getShopId());
                            map.put(sku.getSkuId(), sku);
                        });
                    }
                    shop.getSkus().forEach(sku -> {
                        if (IntegerEnum.NO.getCode().equals(map.get(sku.getSkuId()).getIfOversold())) {
                            //如果不允许超卖,校验redis中商品库存
                            int stockNumber = 0;
                            if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                            } else {
                                stockNumber = map.get(sku.getSkuId()).getStockNumber();
                            }
                            if (sku.getNumber() > stockNumber) {
                                //如果购买数量大于库存，则设置为true
                                flag.set(true);
                            }
                        }
                    });
                }
            }
            //为true则不再售卖
            if (flag.get()) {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
            }
            BigDecimal orderPrice = new BigDecimal(9999);
            //计算订单总金额
            if (param.getProductNo() != null && !param.getProductNo().equals("")) {
                String getCalenderPrice = sendPost.GetCalenderPrice(Integer.valueOf(param.getProductNo()));
                BigDecimal calendar = StringToListCalendar.getCalendar(getCalenderPrice, param.getTravelDate());
                orderPrice = setOrderPrice(map, numberMap, calendar);
            } else {
                orderPrice = setOrderPrice(map, numberMap);
            }
            //查询平台优惠券数据
            CereBuyerCoupon buyerCoupon = cereBuyerCouponService.findByCouponId(param.getCouponId(), user.getBuyerUserId());
            //定义店铺优惠金额map
            Map<Long, CereBuyerShopCoupon> discountMap = new HashMap<>();
            //计算优惠金额
            param.setDiscountPrice(setDiscountPrice(buyerCoupon, param, map, numberMap, discountMap));
            //计算订单实付金额=订单总金额-优惠+运费
            if (!EmptyUtils.isEmpty(logisticPrice)) {
                param.setPrice(orderPrice.subtract(param.getDiscountPrice()).add(logisticPrice));
            } else {
                param.setPrice(orderPrice.subtract(param.getDiscountPrice()));
            }
            //新增父订单数据
            CereOrderParent parent = new CereOrderParent();
            parent.setCreateTime(time);
            parent.setLogisticsPrice(logisticPrice);
            //订单总价
//            if (param.getProductNo()!=null && !param.getProductNo().equals("")){
//                String getCalenderPrice = sendPost.GetCalenderPrice(Integer.valueOf(param.getProductNo()));
//                BigDecimal calendar = StringToListCalendar.getCalendar(getCalenderPrice, param.getTravelDate());
//                BigDecimal bigDecimal = new BigDecimal(param.getShops().get(0).getSkus().get(0).getNumber());
//                BigDecimal multiply = calendar.multiply(bigDecimal);
//                parent.setOrderPrice(multiply);
//            }else {
//                parent.setOrderPrice(orderPrice);
//            }
            parent.setOrderPrice(orderPrice);
            parent.setPrice(param.getPrice());
            parent.setParentFormid(RandomStringUtil.getRandomCode(15, 0));
            cereOrderParentService.insert(parent);
            payUrl.setMoney(param.getPrice());
            payUrl.setOrderId(parent.getParentId());
            if (EmptyUtils.isEmptyBigdecimal(payUrl.getMoney())) {
                //如果金额为0,提示
                throw new CoBusinessException(CoReturnFormat.PAY_MONEY_NOT_ZERO);
            }
            //生成支付二维码
            generatePayUrl(param, user.getWechatOpenId(), parent.getParentFormid(), payUrl.getMoney(), ip, payUrl);

            //遍历店铺数据,新增订单
            addOrder(payUrl, parent.getParentId(), param, user, time, map, buyerCoupon, discountMap, ticketInfo);
        }
    }

    private BigDecimal setOrderPrice(Map<Long, CartSku> map, Map<Long, ProductSku> numberMap) {
        BigDecimal total = new BigDecimal(0);
        for (Long skuId : map.keySet()) {
            total = total.add(map.get(skuId).getPrice().multiply(new BigDecimal(numberMap.get(skuId).getNumber())));
        }
        return total;
    }

    private BigDecimal setOrderPrice(Map<Long, CartSku> map, Map<Long, ProductSku> numberMap, BigDecimal b) {
        BigDecimal total = new BigDecimal(0);
        for (Long skuId : map.keySet()) {
            total = total.add(b.multiply(new BigDecimal(numberMap.get(skuId).getNumber())));
        }
        return total;
    }

    private BigDecimal setDiscountPrice(CereBuyerCoupon buyerCoupon, OrderParam param, Map<Long,
            CartSku> map, Map<Long, ProductSku> numberMap, Map<Long, CereBuyerShopCoupon> discountMap) {
        //定义满足优惠券商品价格总计
        BigDecimal total;
        BigDecimal decimal = new BigDecimal(0);
        if (buyerCoupon != null) {
            //加上平台优惠券
            decimal = decimal.add(buyerCoupon.getReduceMoney());
        }
        //查询所有店铺优惠券数据
        List<CereBuyerShopCoupon> list = cereBuyerShopCouponService.findByIds(param.getShops());
        //计算店铺优惠券金额总和
        if (!EmptyUtils.isEmpty(list)) {
            for (CereBuyerShopCoupon cereBuyerShopCoupon : list) {
                total = new BigDecimal(0);
                if (IntegerEnum.COUPON_TYPE_DISCOUNT.getCode().equals(cereBuyerShopCoupon.getCouponType())) {
                    //如果是折扣券,查询改折扣券关联商品id
                    List<Long> ids = cereBuyerShopCouponService.findProductIds(cereBuyerShopCoupon.getShopCouponId());
                    if (!EmptyUtils.isEmpty(param.getShops())) {
                        //遍历购买商品
                        if (!EmptyUtils.isEmpty(map)) {
                            for (Long key : map.keySet()) {
                                if (ids.contains(map.get(key).getProductId())) {
                                    //如果商品满足优惠券,叠加总计
                                    total = total.add(map.get(key).getPrice().multiply(new BigDecimal(numberMap.get(key).getNumber())));
                                }
                            }
                            //计算折扣价格=总计-总计*折扣
                            BigDecimal price = cereBuyerShopCoupon.getReduceMoney().divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal discount = total.multiply(price).setScale(2, BigDecimal.ROUND_HALF_UP);
                            cereBuyerShopCoupon.setReduceMoney(total.subtract(discount));
                            discountMap.put(cereBuyerShopCoupon.getId(), cereBuyerShopCoupon);
                            decimal = decimal.add(total.subtract(discount));
                        }
                    }
                } else {
                    //如果是满减券直接叠加
                    discountMap.put(cereBuyerShopCoupon.getId(), cereBuyerShopCoupon);
                    decimal = decimal.add(cereBuyerShopCoupon.getReduceMoney());
                }
            }
        }
        return decimal;
    }

    /**
     * 根据不同支付类型生成不同的支付url
     */
    private void generatePayUrl(OrderParam orderParam, String openId, String parentFormId, BigDecimal orderPrice, String ip, PayUrl payUrl) throws Exception {
        Integer paymentMode = orderParam.getPaymentMode();
        Integer subPaymentMode = orderParam.getSubPaymentMode();
        if (paymentMode != null && paymentMode.equals(IntegerEnum.ORDER_PAY_WX.getCode())
                && subPaymentMode != null && subPaymentMode.equals(IntegerEnum.ORDER_SUB_PAYMENT_MODE_H5.getCode())) {
            // h5支付 前端重新调用统一下单
        } else if (paymentMode != null && paymentMode.equals(IntegerEnum.ORDER_PAY_WX.getCode())
                && subPaymentMode != null && subPaymentMode.equals(IntegerEnum.ORDER_SUB_PAYMENT_MODE_XCX.getCode())) {
            // 小程序支付 前端重新调用统一下单
        } else {
            //生成收款码
            String formid = parentFormId + "-" + RandomStringUtil.getRandomCode(3, 0) + "XCX";
            String code_url = wxPayService.getOrderCollectionCode(formid, orderPrice,
                    ip, WxPayEnum.PAY_TYPE_NATIVE.getCode());
            if (!EmptyUtils.isEmpty(code_url)) {
                //生成收款二维码图片
                Map<EncodeHintType, Object> hints = new HashMap<>();
                // 设置纠错等级
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
                // 编码类型
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, 400, 400, hints);
                MatrixToImageConfig config = new MatrixToImageConfig();
                BufferedImage image = toBufferedImage(bitMatrix, config);
                //上传图片到OSS
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(image, "png", out);
                byte[] bytes = out.toByteArray();
                String url = uploadService.uploadByte(formid + ".png", bytes);
                payUrl.setUrl(url);
            }
        }
    }

    @Override
    public OrderPay gotoPay(PayParam param, CereBuyerUser user, String ip) throws CoBusinessException, Exception {
        //.yf,更改为param存的openId
        if (EmptyUtils.isEmpty(user.getWechatOpenId())) {
            throw new CoBusinessException(CoReturnFormat.OPENID_IS_NULL);
        }
        if (!EmptyUtils.isLongEmpty(param.getCollageId())) {
            //定义加锁key
            String key = "拼团订单" + param.getCollageId();
            //加锁
            RLock redissonLock = redisson.getLock(key);
            redissonLock.lock();
            //查询拼单剩余拼团人数
            int person = cereCollageOrderService.findSurplusNumber(param.getCollageId());
            //如果是拼团单支付,查询redis缓存中是否存在该拼单数据
            Object obj = stringRedisService.get(String.valueOf(param.getCollageId()));
            if (EmptyUtils.isEmpty(obj)) {
                //如果没有,说明是发起拼团单第一个支付,放行并将拼单数据放到缓存
                stringRedisService.set(String.valueOf(param.getCollageId()), person);
            } else {
                //如果有,说明是参与拼团支付
                int number = (int) stringRedisService.get(String.valueOf(param.getCollageId()));
                if (number <= 0) {
                    //如果剩余拼团人数小于等于0,拼单已成团,无法支付了
                    throw new CoBusinessException(CoReturnFormat.COLLAGE_ALREADY_SUCCESS, redissonLock);
                } else {
                    //如果大于0,还未成团,修改缓存中剩余拼团人数
                    stringRedisService.set(String.valueOf(param.getCollageId()), number - 1);
                }
            }
            //解锁
            redissonLock.unlock();
        }
        List<Long> shopIds = null;
        String orderFormId = "";
        BigDecimal price = null;
        if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(param.getType())) {
            //父订单提交,查询父订单编号
            CereOrderParent parent = cereOrderParentService.findById(param.getOrderId());
            orderFormId = parent.getParentFormid();
            BigDecimal money = param.getMoney();
//            if (!EmptyUtils.isEmpty(money)){
            price = param.getMoney();
//            }else {
            price = parent.getPrice();
//            }
            //根据父订单查询该订单下所有的店铺id
            shopIds = cereOrderParentService.findShopIds(param.getOrderId());
        } else {
            //子订单提交,查询子订单编号
            CereShopOrder order = cereShopOrderDAO.findById(param.getOrderId());
            orderFormId = order.getOrderFormid();
            BigDecimal money = param.getMoney();
//            if (!EmptyUtils.isEmpty(money)){
            price = param.getMoney();
//            }else {
            price = order.getPrice();
//            }
            //根据子订单查询该订单店铺id
            shopIds = cereShopOrderDAO.findShopId(param.getOrderId());
        }
        System.out.println("支付订单号为：" + orderFormId);
        //调用微信支付接口
        //.YF:改成前端传过OpenId
        Map<String, String> map = wxPayService.gotoPay(orderFormId, price, user.getWechatOpenId(), ip, ParamEnum.PAY_XCX.getCode());
        System.out.println("微信支付返回结果集" + map.toString());
        ObjectMapper mapper = new ObjectMapper();
        OrderPay pay = mapper.readValue(mapper.writeValueAsString(map), OrderPay.class);
        if (!EmptyUtils.isEmpty(shopIds)) {
            List<CereShopConversion> conversions = new ArrayList<>();
            shopIds.forEach(id -> {
                //新增转化数据
                CereShopConversion cereShopConversion = new CereShopConversion();
                cereShopConversion.setShopId(id);
                cereShopConversion.setCreateTime(TimeUtils.yyMMddHHmmss());
                cereShopConversion.setType(ParamEnum.CONVERSION_PAY.getCode());
                conversions.add(cereShopConversion);
            });
            //批量插入转化数据
            cereShopConversionService.insertBatch(conversions);
        }
        return pay;
    }

    @Override
    public OrderPay gotoAppPay(PayParam param, CereBuyerUser user, String ip) throws CoBusinessException, Exception {
        if (EmptyUtils.isEmpty(user.getWechatOpenId())) {
            throw new CoBusinessException(CoReturnFormat.OPENID_IS_NULL);
        }
        //从redis获取已经使用的积分
        Integer usePoints = (Integer) stringRedisService.get(user.getBuyerUserId() + "usePoints");
        //核实该用户积分是否足够
        Integer userPoints = cerePlatformUserPointDao.selectByPoint(user.getBuyerUserId());
        //判断是否积分足够
        int existingPoints = userPoints - usePoints;
        if (existingPoints < param.getPoints()) {
            throw new CoBusinessException(CoReturnFormat.INSUFFICIENT_PAYMENT_POINTS);
        }
        if (!EmptyUtils.isLongEmpty(param.getCollageId())) {
            //定义加锁key
            String key = "拼团订单" + param.getCollageId();
            //加锁
            RLock redissonLock = redisson.getLock(key);
            redissonLock.lock();
            //查询拼单剩余拼团人数
            int person = cereCollageOrderService.findSurplusNumber(param.getCollageId());
            //如果是拼团单支付,查询redis缓存中是否存在该拼单数据
            Object obj = stringRedisService.get(String.valueOf(param.getCollageId()));
            if (EmptyUtils.isEmpty(obj)) {
                //如果没有,说明是发起拼团单第一个支付,放行并将拼单数据放到缓存
                stringRedisService.set(String.valueOf(param.getCollageId()), person);
            } else {
                //如果有,说明是参与拼团支付
                int number = (int) stringRedisService.get(String.valueOf(param.getCollageId()));
                if (number <= 0) {
                    //如果剩余拼团人数小于等于0,拼单已成团,无法支付了
                    throw new CoBusinessException(CoReturnFormat.COLLAGE_ALREADY_SUCCESS, redissonLock);
                } else {
                    //如果大于0,还未成团,修改缓存中剩余拼团人数
                    stringRedisService.set(String.valueOf(param.getCollageId()), number - 1);
                }
            }
            //解锁
            redissonLock.unlock();
        }
        List<Long> shopIds = null;
        String orderFormId = "";
        BigDecimal price = null;
        if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(param.getType())) {
            //父订单提交,查询父订单编号
            CereOrderParent parent = cereOrderParentService.findById(param.getOrderId());
            orderFormId = parent.getParentFormid();
            //减去积分抵扣
            price = parent.getPrice().subtract(new BigDecimal(param.getPoints()));
            //根据父订单查询该订单下所有的店铺id
            shopIds = cereOrderParentService.findShopIds(param.getOrderId());
        } else {
            //子订单提交,查询子订单编号
            CereShopOrder order = cereShopOrderDAO.findById(param.getOrderId());
            orderFormId = order.getOrderFormid();
            //减去积分抵扣
            price = order.getPrice().subtract(new BigDecimal(param.getPoints()));
            //根据子订单查询该订单店铺id
            shopIds = cereShopOrderDAO.findShopId(param.getOrderId());
        }

        //把暂时没有成功支付的积分保存起来，等到支付成功后再加入已经使用的积分中
        stringRedisService.set(user.getBuyerUserId() + "ToBeSettled", param.getPoints());

        //调用微信支付接口
        Map<String, String> map = wxPayService.gotoPay(orderFormId, price, user.getWechatOpenId(), ip, ParamEnum.PAY_APP.getCode());
        ObjectMapper mapper = new ObjectMapper();
        OrderPay pay = mapper.readValue(mapper.writeValueAsString(map), OrderPay.class);
        if (!EmptyUtils.isEmpty(shopIds)) {
            List<CereShopConversion> conversions = new ArrayList<>();
            shopIds.forEach(id -> {
                //新增转化数据
                CereShopConversion cereShopConversion = new CereShopConversion();
                cereShopConversion.setShopId(id);
                cereShopConversion.setCreateTime(TimeUtils.yyMMddHHmmss());
                cereShopConversion.setType(ParamEnum.CONVERSION_PAY.getCode());
                conversions.add(cereShopConversion);
            });
            //批量插入转化数据
            cereShopConversionService.insertBatch(conversions);
        }
        return pay;
    }

    @Override
    public OrderPay gotoH5Pay(PayParam param, CereBuyerUser user, String ip) throws CoBusinessException, Exception {
        //从redis获取已经使用的积分
        Integer usePoints = (Integer) stringRedisService.get(user.getBuyerUserId() + "usePoints");
        //总积分核实该用户积分是否足够
        Integer userPoints = cerePlatformUserPointDao.selectByPoint(user.getBuyerUserId());
        //判断是否积分足够
        if (EmptyUtils.isEmpty(usePoints)) {
            usePoints = 0;
        }
        if (EmptyUtils.isEmpty(userPoints)) {
            userPoints = 0;
        }
        int existingPoints = userPoints - usePoints;
        if (EmptyUtils.isEmpty(param.getPoints())) {
            param.setPoints(0);
        }
        if (existingPoints < param.getPoints()) {
            throw new CoBusinessException(CoReturnFormat.INSUFFICIENT_PAYMENT_POINTS);
        }
        List<Long> shopIds = null;
        String orderFormId = "";
        BigDecimal price = null;
        if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(param.getType())) {
            //父订单提交,查询父订单编号
            CereOrderParent parent = cereOrderParentService.findById(param.getOrderId());
            orderFormId = parent.getParentFormid();
            //减去积分抵扣
            price = parent.getPrice().subtract(new BigDecimal(param.getPoints()));
            //根据父订单查询该订单下所有的店铺id
            shopIds = cereOrderParentService.findShopIds(param.getOrderId());
        } else {
            //子订单提交,查询子订单编号
            CereShopOrder order = cereShopOrderDAO.findById(param.getOrderId());
            orderFormId = order.getOrderFormid();
            price = order.getPrice().subtract(new BigDecimal(param.getPoints()));
            //根据子订单查询该订单店铺id
            shopIds = cereShopOrderDAO.findShopId(param.getOrderId());
        }

        //把暂时没有成功支付的积分保存起来，等到支付成功后再加入已经使用的积分中
        stringRedisService.set(user.getBuyerUserId() + "ToBeSettled", param.getPoints());

        //调用微信支付接口
        Map<String, String> map = wxPayService.gotoPay(orderFormId, price, user.getWechatOpenId(), ip, ParamEnum.PAY_XCX.getCode());
        ObjectMapper mapper = new ObjectMapper();
        OrderPay pay = mapper.readValue(mapper.writeValueAsString(map), OrderPay.class);
        if (!EmptyUtils.isEmpty(shopIds)) {
            List<CereShopConversion> conversions = new ArrayList<>();
            shopIds.forEach(id -> {
                //新增转化数据
                CereShopConversion cereShopConversion = new CereShopConversion();
                cereShopConversion.setShopId(id);
                cereShopConversion.setCreateTime(TimeUtils.yyMMddHHmmss());
                cereShopConversion.setType(ParamEnum.CONVERSION_PAY.getCode());
                conversions.add(cereShopConversion);
            });
            //批量插入转化数据
            cereShopConversionService.insertBatch(conversions);
        }
        return pay;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void handleWxLog(String orderFormId, String transactionId, String orderNo) throws Exception {
        String time = TimeUtils.yyMMddHHmmss();
        List<CereShopOrder> list = null;
        //查询是否为父订单编号
        CereOrderParent parent = cereShopOrderDAO.findByParentFormid(orderFormId);
        if (parent != null) {
            //查询所有子订单数据
            list = cereShopOrderDAO.findByParentId(parent.getParentId());
        } else {
            //子订单支付回调
            list = cereShopOrderDAO.findByFormid(orderFormId);
        }
        //支付业务处理
        if (!EmptyUtils.isEmpty(list)) {
            List<CereDistributionOrder> distributionOrders = new ArrayList<>();
            List<CereShopConversion> conversions = new ArrayList<>();
            for (CereShopOrder order : list) {
                if (!EmptyUtils.isEmpty(order.getShopGroupWorkId())) {
                    //拼单支付业务处理
                    handleGroupWork(order, transactionId, orderNo, time);
                } else if (!EmptyUtils.isEmpty(order.getShopSeckillId())) {
                    //秒杀活动支付业务处理
                    handleSeckill(order, transactionId, orderNo, time);
                } else if (!EmptyUtils.isEmpty(order.getShopDiscountId())) {
                    //限时折扣活动支付业务处理
                    handleDiscount(order, transactionId, orderNo, time);
                } else {
                    //正常下单业务处理
                    handleOrder(order, transactionId, orderNo, time, distributionOrders, conversions);
                }
                //推送通信
                websocket.sendMessage(order.getShopId(), "1");
            }
            if (!EmptyUtils.isEmpty(distributionOrders)) {
                //批量插入分销订单数据
                cereDistributionOrderService.insertBatch(distributionOrders);
            }
            if (!EmptyUtils.isEmpty(conversions)) {
                //批量插入转化数据
                cereShopConversionService.insertBatch(conversions);
            }
        }


    }


    private void handleSeckill(CereShopOrder order, String transactionId, String orderNo, String time) throws Exception {
        //查询秒杀活动数据
        CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(order.getShopSeckillId());
        if (cereShopSeckill != null) {
            //修改订单支付状态和订单状态
            order.setUpdateTime(time);
            order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
            order.setPaymentTime(time);
            order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);
            //新增订单对账数据
            addReconciliation(order, time);
            //新增支付流水数据
            addPayLog(order, time, orderNo, transactionId);
            //删除自动关闭订单延时任务
            stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            //删除延时任务记录
            cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            if (IntegerEnum.YES.getCode().equals(cereShopSeckill.getIfNumber())) {
                //如果限量,查询活动商品剩余件数
                CereShopSeckillDetail detail = cereShopSeckillDetailService.findSkuDetail(order.getShopSeckillId(), order.getOrderId());
                if (detail != null) {
                    //查询订单商品购买数量
                    int number = cereShopOrderDAO.findOrderNumber(order.getOrderId());
                    //扣除订单购买数量
                    detail.setNumber(detail.getNumber() - number);
                    cereShopSeckillDetailService.updateNumber(detail);
                }
            }
            //新增订单支付成功消息
            CereNotice cereNotice = new CereNotice();
            cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
            cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
            cereNotice.setBuyerUserId(order.getBuyerUserId());
            cereNotice.setShopId(order.getShopId());
            cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_PAY_SUCCESS.getCode());
            cereNotice.setNoticeContent("您购买的" + order.getOrderFormid() + "已支付成功，请耐心等待商家发货");
            cereNotice.setOnly(order.getOrderId());
            cereNotice.setCreateTime(time);
            cereNotice.setIfRead(IntegerEnum.NO.getCode());
            cereNoticeService.insert(cereNotice);
        }
    }

    private void handleDiscount(CereShopOrder order, String transactionId, String orderNo, String time) throws Exception {
        //查询限时折扣活动数据
        CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(order.getShopDiscountId());
        if (cereShopDiscount != null) {
            //修改订单支付状态和订单状态
            order.setUpdateTime(time);
            order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
            order.setPaymentTime(time);
            order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);
            //新增订单对账数据
            addReconciliation(order, time);
            //新增支付流水数据
            addPayLog(order, time, orderNo, transactionId);
            //删除自动关闭订单延时任务
            stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            //删除延时任务记录
            cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            if (IntegerEnum.YES.getCode().equals(cereShopDiscount.getIfNumber())) {
                //如果限量,查询活动商品剩余件数
                CereShopDiscountDetail detail = cereShopDiscountDetailService.findSkuDetail(order.getShopDiscountId(), order.getOrderId());
                if (detail != null) {
                    //查询订单商品购买数量
                    int number = cereShopOrderDAO.findOrderNumber(order.getOrderId());
                    //扣除订单购买数量
                    detail.setNumber(detail.getNumber() - number);
                    cereShopDiscountDetailService.updateNumber(detail);
                }
            }
            //新增订单支付成功消息
            CereNotice cereNotice = new CereNotice();
            cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
            cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
            cereNotice.setBuyerUserId(order.getBuyerUserId());
            cereNotice.setShopId(order.getShopId());
            cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_PAY_SUCCESS.getCode());
            cereNotice.setNoticeContent("您购买的" + order.getOrderFormid() + "已支付成功，请耐心等待商家发货");
            cereNotice.setOnly(order.getOrderId());
            cereNotice.setCreateTime(time);
            cereNotice.setIfRead(IntegerEnum.NO.getCode());
            cereNoticeService.insert(cereNotice);
        }
    }

    private void handleOrder(CereShopOrder order, String transactionId, String orderNo, String time,
                             List<CereDistributionOrder> distributionOrders, List<CereShopConversion> conversions) throws Exception {
        //.根据订单Id拿到订单商品信息拿到具体的商品Id,判断productNo是否为空,如果为空,则是普通商品,如果不为空则是票务商品
        //根据订单序号拿到订单商品信息里的数量，以及商品序号
//        CereOrderProduct cereOrderProduct = dlCereOrderProductService.findCereOrderProductByOrderId(order.getOrderId());
        List<CereOrderProduct> cereOrderProductByOrderId = dlCereOrderProductService.findCereOrderProductByOrderId(order.getOrderId());
        //w判断长度, 不等于1,就是购物车购买
        int size = cereOrderProductByOrderId.size();
        //w票订单进里面, 其他订单走else
        CereOrderProduct c1 = cereOrderProductByOrderId.get(0);
        CereShopProduct c2 = dlCereOrderProductService.findCereShopProductByProductId(c1.getProductId());
        if (size == 1 && !EmptyUtils.isEmpty(c2.getProductNo())) {
            CereOrderProduct cereOrderProduct = cereOrderProductByOrderId.get(0);
            //根据商品序号拿到商品信息表里的productNo
            CereShopProduct cereShopProduct = dlCereOrderProductService.findCereShopProductByProductId(cereOrderProduct.getProductId());
            //判断ProductNo如果不为空则代表是票务下单
            if (!EmptyUtils.isEmpty(cereShopProduct.getProductNo())) {
                //根据商品序号,拿到价格
                CereProductSku cereProductSku = dlCereOrderProductService.findCereProductSkuByProductId(cereOrderProduct.getProductId());
                //根据订单序号拿到订单附属表
                CereShopTicketInfo cereShopTicketInfo = dlCereOrderProductService.findCereShopTicketInfoByOrderId(order.getOrderId());
                //修改时间,返回第二天时间
                String date = StringToDate(cereShopTicketInfo.getTravelDate());
                //.价格做运算
                BigDecimal price = cereProductSku.getPrice();
                BigDecimal bigDecimal = BigDecimal.valueOf(100);
                long value = bigDecimal.multiply(price).longValue();
                //向助销客下单(第一个价格是售价，第二个价格是原价)
                ResultYf resultYf = sendPost.CreateOrder(String.valueOf(order.getOrderFormid()), cereShopProduct.getProductNo(), 1, cereOrderProduct.getNumber(), value
                        , value, cereShopTicketInfo.getCustomer(),
                        cereShopTicketInfo.getCustomerTel(), cereShopTicketInfo.getCustomerCard(), cereShopTicketInfo.getTravelDate(), date, null, null,
                        null, null);
                //判断返回参数是否成功
                if (resultYf.getResult()) {
                    String message = resultYf.getMessage();
                    String partnerOrderId = (String) JsonUtils.toMap(message).get("partnerOrderId");
                    String partnerCode = (String) JsonUtils.toMap(message).get("partnerCode");
                    String partnerQRCodeAddress = (String) JsonUtils.toMap(message).get("partnerQRCodeAddress");
                    //.如果调用成功则直接添加数据库三个参数
                    dlCereOrderProductDao.setMessageByOrderId(order.getOrderId(), partnerOrderId, partnerCode, partnerQRCodeAddress);
                } else {
                    order.setState(IntegerEnum.ORDER_HAVE_DILEVERY.getCode());
                    System.out.println(IntegerEnum.ORDER_HAVE_DILEVERY.getCode());
                }
                //并改成已返货
                order.setState(IntegerEnum.ORDER_HAVE_DILEVERY.getCode());
                System.out.println(IntegerEnum.ORDER_HAVE_DILEVERY.getCode());
            }
        } else {
            //如果productNo为空,则修改订单状态为待发货
            order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
            System.out.println(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
        }

        //修改订单支付状态和订单状态
        order.setUpdateTime(time);
        order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
        order.setPaymentTime(time);
        //添加券码
        if (c2.getClassifyId() == 8 || c2.getClassifyId() == 9) {
            //随机券码
            order.setCouponCode(RandomStringUtil.getRandomCode(8, 4));
            order.setIsUse(1);
            order.setState(3);
        }

        //校验当前客户是否为分销员
//        if (!EmptyUtils.isEmpty(order.getCustomerPhone())) {
        //查询分销数据
        ShopDistributor distributor = cereShopDistributorService.findById(order.getSharerId());
//        }
//        if(distributor!=null){
//            if(IntegerEnum.YES.getCode().equals(distributor.getIfSelf())){
//                //当前客户就是分销员,并且开启了自购分佣,新增分销订单数据
//                addDistributor(distributor,order,time,distributionOrders);
//            }
//        }else {
        //如果客户不是分销员,判断是否绑定其他分销员
//        distributor = cereDistributorBuyerService.findByUserId(order.getBuyerUserId());
//        if (distributor != null) {
//            //如果绑定了,新增分销订单数据
        //如果没有找到,说明没有分享人,则不用添加
        if (distributor != null) {
            //...积分商品没有分佣
            addDistributor(distributor, order, time, distributionOrders);
        }
////            }
//        }
        //修改状态
        cereShopOrderDAO.updateByPrimaryKeySelective(order);

        //查询数据库是否有这个订单编号
        //新增订单对账数据
        addReconciliation(order, time);
        //新增支付流水数据
        addPayLog(order, time, orderNo, transactionId);
        //新增转化数据
        CereShopConversion cereShopConversion = new CereShopConversion();
        cereShopConversion.setType(ParamEnum.CONVERSION_PAY_SUCCESS.getCode());
        cereShopConversion.setShopId(order.getShopId());
        cereShopConversion.setCreateTime(time);
        conversions.add(cereShopConversion);
        //删除自动关闭订单延时任务
        stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
        //删除延时任务记录
        cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
        //新增订单支付成功消息
        CereNotice cereNotice = new CereNotice();
        cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
        cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
        cereNotice.setBuyerUserId(order.getBuyerUserId());
        cereNotice.setShopId(order.getShopId());
        cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_PAY_SUCCESS.getCode());
        cereNotice.setNoticeContent("您购买的" + order.getOrderFormid() + "已支付成功，请耐心等待商家发货");
        cereNotice.setOnly(order.getOrderId());
        cereNotice.setCreateTime(time);
        cereNotice.setIfRead(IntegerEnum.NO.getCode());

        cereNoticeService.insert(cereNotice);
    }


    private void handleGroupWork(CereShopOrder order, String transactionId, String orderNo, String time) throws Exception {
        //根据订单id和拼团活动id查询拼单数据
        CereCollageOrder cereCollageOrder = cereCollageOrderService.findByOrder(order);
        if (cereCollageOrder != null) {
            //修改订单支付状态和订单状态
            order.setUpdateTime(time);
            order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
            order.setPaymentTime(time);
            //新增订单对账数据
            addReconciliation(order, time);
            //新增支付流水数据
            addPayLog(order, time, orderNo, transactionId);
            if (cereCollageOrder.getSurplusNumber() > 1) {
                //待成团业务处理,拼单剩余拼团人数-1
                cereCollageOrder.setSurplusNumber(cereCollageOrder.getSurplusNumber() - 1);
                cereCollageOrder.setUpdateTime(time);
                cereCollageOrderService.update(cereCollageOrder);
                //修改订单状态为待成团
                order.setState(IntegerEnum.ORDER_STAY_COLLAGE.getCode());
            } else {
                //拼团成功业务处理,状态改为拼团成功
                cereCollageOrder.setUpdateTime(time);
                cereCollageOrder.setState(IntegerEnum.COLLAGE_STATE_SUCCESS.getCode());
                cereCollageOrder.setSurplusNumber(0);
                cereCollageOrderService.update(cereCollageOrder);
                //查询所有参与拼团的未支付的订单数据,当前订单除外,修改为失效订单
                List<Long> ids = cereCollageOrderService.findNotPayCollageOrderIds(cereCollageOrder.getCollageId(), order.getOrderId());
                if (!EmptyUtils.isEmpty(ids)) {
                    cereCollageOrderDetailService.updateInvalid(ids);
                    //取消所有的失效订单
                    cancelBatch(ids);
                }
                //查询所有参与拼团支付过的订单数据,当前订单除外,修改为待发货
                List<CereShopOrder> orders = cereCollageOrderService.findPayCollageOrderIds(cereCollageOrder.getCollageId(), order.getOrderId());
                if (!EmptyUtils.isEmpty(orders)) {
                    //批量修改订单状态
                    cereShopOrderDAO.updateBatch(orders, IntegerEnum.ORDER_STAY_DILEVERY.getCode(), time);
                    //封装支付成功消息
                    List<CereNotice> notices = orders.stream().map(cereShopOrder -> {
                        CereNotice cereNotice = new CereNotice();
                        cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
                        cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
                        cereNotice.setBuyerUserId(cereShopOrder.getBuyerUserId());
                        cereNotice.setShopId(cereShopOrder.getShopId());
                        cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_PAY_SUCCESS.getCode());
                        cereNotice.setNoticeContent("您购买的" + cereShopOrder.getOrderFormid() + "已支付成功，请耐心等待商家发货");
                        cereNotice.setOnly(cereShopOrder.getOrderId());
                        cereNotice.setIfRead(IntegerEnum.NO.getCode());
                        cereNotice.setCreateTime(time);
                        return cereNotice;
                    }).collect(Collectors.toList());
                    //批量插入消息
                    cereNoticeService.insertBatch(notices);
                }
                //删除拼团失败延时任务
                stringRedisService.delete(StringEnum.COLLAGE_ERROR.getCode() + "-" + cereCollageOrder.getCollageId());
                cereRedisKeyServcice.deleteByKey(StringEnum.COLLAGE_ERROR.getCode() + "-" + cereCollageOrder.getCollageId());
                //修改订单状态为待发货
                order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
                //新增订单支付成功消息
                CereNotice cereNotice = new CereNotice();
                cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
                cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
                cereNotice.setBuyerUserId(order.getBuyerUserId());
                cereNotice.setShopId(order.getShopId());
                cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_PAY_SUCCESS.getCode());
                cereNotice.setNoticeContent("您购买的" + order.getOrderFormid() + "已支付成功，请耐心等待商家发货");
                cereNotice.setOnly(order.getOrderId());
                cereNotice.setCreateTime(time);
                cereNotice.setIfRead(IntegerEnum.NO.getCode());
                cereNoticeService.insert(cereNotice);
            }
            cereShopOrderDAO.updateByPrimaryKeySelective(order);
        }
    }


    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void handleRefundWxLog(String orderFormId, String transaction_id, String orderNo) throws Exception {
        String time = TimeUtils.yyMMddHHmmss();
        //查询订单数据
        CereShopOrder order = cereShopOrderDAO.findByOrderFormid(orderFormId);
        if (order != null) {
            //更新订单状态为已取消
            order.setUpdateTime(time);
            order.setState(IntegerEnum.ORDER_STOP.getCode());
            order.setPrice(new BigDecimal(0));
            order.setPaymentState(IntegerEnum.NO.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);
            cereShopOrderDAO.updateByOrderId(order.getOrderId());
            //新增对账单数据
            CereOrderReconciliation reconciliation = new CereOrderReconciliation();
            reconciliation.setOrderId(order.getOrderId());
            reconciliation.setMoney(order.getPrice());
            reconciliation.setState(IntegerEnum.RELATIONSHIP_SOLVE_FROZEN.getCode());
            reconciliation.setType(IntegerEnum.RELATIONSHIP_ONCOME.getCode());
            reconciliation.setCreateTime(time);
            cereOrderReconciliationService.insert(reconciliation);
            //查询支付流水
            CerePayLog cerePayLog = cereShopOrderDAO.findPayLog(orderFormId);
            //插入退款流水
            CerePayLog payLog = new CerePayLog();
            payLog.setCreateTime(time);
            payLog.setOrderFormid(order.getOrderFormid());
            payLog.setOutTradeNo(orderNo);
            payLog.setTransactionId(transaction_id);
            payLog.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
            payLog.setShopId(order.getShopId());
            payLog.setState(StringEnum.PAY_LOG_REFUND.getCode());
            payLog.setTotalFee(order.getPrice());
            payLog.setUserId(String.valueOf(order.getBuyerUserId()));
            payLog.setRemark(order.getCustomerName() + "取消订单退款" + order.getPrice() + "元,退款单号为：" + cerePayLog.getOutRefundNo()
                    + ",退款时间为" + time);
            cerePayLogService.insert(payLog);
        }
    }

    @Override
    public SettlementShop findSettlementShop(Long shopId) {
        return cereShopOrderDAO.findSettlementShop(shopId);
    }

    public void handleRefundTestWxLog(String orderFormId, String transaction_id, String orderNo) throws Exception {
        String time = TimeUtils.yyMMddHHmmss();
        //查询订单数据
        CereShopOrder order = cereShopOrderDAO.findByOrderFormid(orderFormId);
        if (order != null) {
            //更新订单状态为已取消
            order.setUpdateTime(time);
            order.setState(IntegerEnum.ORDER_STOP.getCode());
            order.setPrice(new BigDecimal(0));
            order.setPaymentState(IntegerEnum.NO.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);
            cereShopOrderDAO.updateByOrderId(order.getOrderId());
            //新增对账单数据
            CereOrderReconciliation reconciliation = new CereOrderReconciliation();
            reconciliation.setOrderId(order.getOrderId());
            reconciliation.setMoney(order.getPrice());
            reconciliation.setState(IntegerEnum.RELATIONSHIP_SOLVE_FROZEN.getCode());
            reconciliation.setType(IntegerEnum.RELATIONSHIP_ONCOME.getCode());
            reconciliation.setCreateTime(time);
            cereOrderReconciliationService.insert(reconciliation);
            //查询支付流水
            CerePayLog cerePayLog = cereShopOrderDAO.findPayLog(orderFormId);
            //插入退款流水
            CerePayLog payLog = new CerePayLog();
            payLog.setCreateTime(time);
            payLog.setOrderFormid(order.getOrderFormid());
            payLog.setOutTradeNo(orderNo);
            payLog.setOutRefundNo(cerePayLog.getOutRefundNo());
            payLog.setTransactionId(transaction_id);
            payLog.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
            payLog.setShopId(order.getShopId());
            payLog.setState(StringEnum.PAY_LOG_REFUND.getCode());
            payLog.setTotalFee(order.getPrice());
            payLog.setUserId(String.valueOf(order.getBuyerUserId()));
            payLog.setRemark(order.getCustomerName() + "取消订单退款" + order.getPrice() + "元,退款单号为：" + cerePayLog.getOutRefundNo()
                    + ",退款时间为" + time);
            cerePayLogService.insert(payLog);
        }
    }

    @Override
    public Page getAll(OrderGetAllParam param, CereBuyerUser user) throws CoBusinessException {
        param.setBuyerUserId(user.getBuyerUserId());
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Orders> list = cereShopOrderDAO.getAll(param);
        if (!EmptyUtils.isEmpty(list)) {
            list.forEach(orders -> {
                //查询订单商品明细数据
                List<CartSku> skus = cereOrderProductService.findOrderProductSku(orders.getOrderId());
                if (!EmptyUtils.isEmpty(skus)) {
                    //设置规格值数组
                    skus.forEach(sku -> sku.setValues(EmptyUtils.getImages(sku.getValue())));
                }
                //查询该订单已评价商品数量
                int comment = cereShopCommentService.findProductNumber(orders.getOrderId());
                if (skus.size() == comment) {
                    //该订单商品全部已评价
                    orders.setIfNotComment(IntegerEnum.NO.getCode());
                } else {
                    orders.setIfNotComment(IntegerEnum.YES.getCode());
                }
                orders.setSkus(skus);
            });
        }
        for (Orders orders : list) {
            for (CartSku skus : orders.getSkus()) {
                Long productId = skus.getProductId();
                Integer state = cereShopProductService.getsheStateByid(productId);
                skus.setShelveState(state);
                if (skus.getClassifyId() != null && skus.getClassifyId() == 7) {
                    skus.setPrice(skus.getPrice().multiply(new BigDecimal(10)));
                    skus.setTotal(skus.getTotal().multiply(new BigDecimal(10)));
                    orders.setOrderPrice(orders.getOrderPrice().multiply(new BigDecimal(10)));
                }
            }
        }
        PageInfo<Orders> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public OrderDetail getById(OrderGetByIdParam param) throws CoBusinessException, Exception {
        Long orderId = param.getOrderId();
        if (!EmptyUtils.isLongEmpty(param.getNoticeId())) {
            //更新已读状态
            CereNotice cereNotice = new CereNotice();
            cereNotice.setIfRead(IntegerEnum.YES.getCode());
            cereNotice.setNoticeId(param.getNoticeId());
            cereNoticeService.update(cereNotice);
        }
        OrderDetail detail = cereShopOrderDAO.getById(orderId);
        //YF:根据orderId查询出附属表数据并赋值返回到前端
        CereShopTicketInfo cereShopTicketInfo = dlCereOrderProductService.findCereShopTicketInfoByOrderId(orderId);
        if (cereShopTicketInfo != null) {
            detail.setTicketInfoId(cereShopTicketInfo.getTicketInfoId());
            detail.setCustomer(cereShopTicketInfo.getCustomer());
            detail.setCustomerTel(cereShopTicketInfo.getCustomerTel());
            detail.setCustomerCard(cereShopTicketInfo.getCustomerCard());
            detail.setMemo(cereShopTicketInfo.getMemo());
            detail.setTravelDate(cereShopTicketInfo.getTravelDate());
            //YF:根据orderId查询出产品信息，并赋值productNo产品编号
//            CereOrderProduct product = dlCereOrderProductService.findCereOrderProductByOrderId(orderId);
            List<CereOrderProduct> cereOrderProductByOrderId = dlCereOrderProductService.findCereOrderProductByOrderId(orderId);
            CereOrderProduct product = cereOrderProductByOrderId.get(0);
            CereShopProduct cereShopProduct = dlCereOrderProductService.findCereShopProductByProductId(product.getProductId());
            if (cereShopProduct != null) {
                detail.setProductNo(cereShopProduct.getProductNo());
            }
        }

        if (detail != null) {
            //查询订单商品明细
            List<CartSku> skus = cereOrderProductService.findOrderProductSku(detail.getOrderId());
            for (CartSku cartSku : skus) {
                if (cartSku.getClassifyId() != null && cartSku.getClassifyId() == 7) {
                    cartSku.setPrice(cartSku.getPrice().multiply(new BigDecimal(10)));
                    cartSku.setTotal(cartSku.getTotal().multiply(new BigDecimal(10)));
                    detail.setPrice(cartSku.getPrice());
                    detail.setOrderPrice(cartSku.getPrice());
                }
            }
            if (!EmptyUtils.isEmpty(skus)) {
                //设置规格值数组
                skus.forEach(sku -> sku.setValues(EmptyUtils.getImages(sku.getValue())));
            }
            detail.setSkus(skus);
            //计算自动关闭订单倒计时
            detail.setTime(30 * 60 * 1000 - TimeUtils.getCountDownByTime(detail.getCreateTime(), TimeUtils.yyMMddHHmmss()));
            if (!EmptyUtils.isEmpty(detail.getShopGroupWorkId())) {
                //查询拼团信息数据
                CollageDetail collageDetail = cereCollageOrderService.findDetail(detail.getShopGroupWorkId(), detail.getOrderId());
                if (collageDetail != null) {
                    //计算成团有效时间=拼单的发起时间延时拼团活动设置的有效时长后的时间
                    String time = TimeUtils.getMoreHourAfter(collageDetail.getCreateTime(), collageDetail.getEffectiveTime());
                    //设置成团倒计时时间
                    collageDetail.setTime(TimeUtils.getCountDownByTime(TimeUtils.yyMMddHHmmss(), time));
                    //查询参与拼团人员信息
                    collageDetail.setPersonList(cereCollageOrderService.findPersons(collageDetail.getCollageId()));
                    detail.setCollageDetail(collageDetail);
                }
            }
        }

        //添加优惠券信息
        CereShopOrder cereShopOrder = cereShopOrderDAO.selectByPrimaryKey(orderId);
        //如果是已经使用,则查找核销时间
        if (cereShopOrder.getIsUse() != null && cereShopOrder.getIsUse() == 2) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("couponCode", cereShopOrder.getCouponCode());
            List<CereShopCouponRecording> list = cereShopCouponRecordingDao.list(map);
            if (list != null && list.size() != 0) {
                detail.setUseTime(list.get(0).getCreateTime());
            }
        }
        detail.setCouponCode(cereShopOrder.getCouponCode());
        detail.setIsUse(cereShopOrder.getIsUse());
        return detail;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void confirm(OrderGetByIdParam param, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        //校验当前订单状态是否为待收货
        CereShopOrder cereShopOrder = cereShopOrderDAO.checkState(param.getOrderId(), IntegerEnum.ORDER_HAVE_DILEVERY.getCode());
        if (cereShopOrder == null) {
            throw new CoBusinessException(CoReturnFormat.ORDER_NOT_TAKE);
        }
        //修改订单状态为已完成
        CereShopOrder order = cereShopOrderDAO.selectByPrimaryKey(param.getOrderId());
        order.setOrderId(param.getOrderId());
        order.setUpdateTime(time);
        order.setState(IntegerEnum.ORDER_FINISH.getCode());
        order.setReceiveTime(time);
        cereShopOrderDAO.updateByPrimaryKeySelective(order);
        //删除自动确认收货延时任务
        stringRedisService.delete(StringEnum.ORDER_CONFIRM_DILEVERY.getCode() + "-" + param.getOrderId());
        cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_CONFIRM_DILEVERY.getCode() + "-" + param.getOrderId());
        //修改订单对账单状态为解冻
        CereOrderReconciliation reconciliation = new CereOrderReconciliation();
        reconciliation.setOrderId(param.getOrderId());
        reconciliation.setState(IntegerEnum.RELATIONSHIP_SOLVE_FROZEN.getCode());
        reconciliation.setUpdateTime(time);
        cereOrderReconciliationService.updateByOrderId(reconciliation);
        //新增订单已完成消息
        CereNotice cereNotice = new CereNotice();
        cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
        cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
        cereNotice.setBuyerUserId(order.getBuyerUserId());
        cereNotice.setShopId(order.getShopId());
        cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_FINISH.getCode());
        cereNotice.setNoticeContent("订单" + order.getOrderFormid() + "已确认收货，期待您分享商品评价和购物心得");
        cereNotice.setOnly(order.getOrderId());
        cereNotice.setCreateTime(time);
        cereNotice.setIfRead(IntegerEnum.NO.getCode());
        cereNoticeService.insert(cereNotice);

        //把退款请求取消


    }

    @Override
    public void update(CereShopOrder cereShopOrder) throws CoBusinessException {
        cereShopOrderDAO.updateByPrimaryKeySelective(cereShopOrder);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void cancel(OrderGetByIdParam param, CereBuyerUser user) throws CoBusinessException, Exception {
        String time = TimeUtils.yyMMddHHmmss();
        //校验当前订单状态是否为待付款或者待发货或者待成团
        CereShopOrder cereShopOrder = cereShopOrderDAO.checkCancelState(param.getOrderId());
        if (cereShopOrder == null) {
            throw new CoBusinessException(CoReturnFormat.ORDER_NOT_TAKE);
        }
        //修改订单状态为已取消
        CereShopOrder order = new CereShopOrder();
        order.setOrderId(param.getOrderId());
        order.setUpdateTime(time);
        order.setState(IntegerEnum.ORDER_STOP.getCode());
        cereShopOrderDAO.updateByPrimaryKeySelective(order);
        //todo 修改退款状态
        cereShopOrderDAO.updateByOrderId(param.getOrderId());
        if (!EmptyUtils.isEmpty(cereShopOrder.getCouponId())) {
            //修改平台优惠券状态为已领取
            CereBuyerCoupon cereBuyerCoupon = new CereBuyerCoupon();
            cereBuyerCoupon.setBuyerUserId(user.getBuyerUserId());
            cereBuyerCoupon.setCouponId(cereShopOrder.getCouponId());
            cereBuyerCoupon.setUpdateTime(time);
            cereBuyerCoupon.setState(IntegerEnum.COUPON_HAVE.getCode());
            cereBuyerCouponService.updateByUserIdAndCouponId(cereBuyerCoupon);
        }
        if (!EmptyUtils.isEmpty(cereShopOrder.getId())) {
            //修改店铺优惠券状态为已领取
            CereBuyerShopCoupon cereBuyerShopCoupon = new CereBuyerShopCoupon();
            cereBuyerShopCoupon.setId(cereShopOrder.getId());
            cereBuyerShopCoupon.setUpdateTime(time);
            cereBuyerShopCoupon.setState(IntegerEnum.COUPON_HAVE.getCode());
            cereBuyerShopCouponService.updateState(cereBuyerShopCoupon);
        }
        if (!EmptyUtils.isLongEmpty(cereShopOrder.getShopGroupWorkId())) {
            //查询当前订单是否为开团用户
            CereCollageOrder cereCollageOrder = cereCollageOrderService.findByUserId(user.getBuyerUserId(), order.getOrderId());
            if (cereCollageOrder != null) {
                //修改拼单状态为失败
                cereCollageOrder.setUpdateTime(time);
                cereCollageOrder.setState(IntegerEnum.COLLAGE_STATE_ERROR.getCode());
                cereCollageOrderService.update(cereCollageOrder);
                //查询参与该拼单的订单数据
                List<Long> ids = cereCollageOrderService.findOrderIds(cereCollageOrder.getCollageId());
                //修改拼单明细订单改为已失效,并且订单自动取消
                if (!EmptyUtils.isEmpty(ids)) {
                    cereCollageOrderDetailService.updateInvalid(ids);
                    //过滤当前订单id
                    ids = ids.stream().filter(id -> !id.equals(cereShopOrder.getOrderId())).collect(Collectors.toList());
                    if (!EmptyUtils.isEmpty(ids)) {
                        //批量取消订单
                        cancelBatch(ids);
                    }
                }
            }
        }
        if (!EmptyUtils.isEmpty(cereShopOrder.getShopSeckillId())) {
            //查询秒杀活动数据
            CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(cereShopOrder.getShopSeckillId());
            if (IntegerEnum.YES.getCode().equals(cereShopSeckill.getIfNumber())) {
                //如果限量,需要更新限量库存数据
                List<CereShopSeckillDetail> seckillDetails = cereShopSeckillDetailService.findNumberDetails(cereShopOrder.getOrderId(), cereShopSeckill.getShopSeckillId());
                if (!EmptyUtils.isEmpty(seckillDetails)) {
                    //更新redis限量库存
                    seckillDetails.forEach(detail -> {
                        stringRedisService.set("秒杀活动商品仅剩件数" + detail.getShopSeckillId() + detail.getSkuId(), detail.getNumber());
                    });
                    cereShopSeckillDetailService.updateBatch(seckillDetails);
                }
            }
        }
        if (!EmptyUtils.isEmpty(cereShopOrder.getShopDiscountId())) {
            //查询秒杀活动数据
            CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(cereShopOrder.getShopDiscountId());
            if (IntegerEnum.YES.getCode().equals(cereShopDiscount.getIfNumber())) {
                //如果限量,需要更新限量库存数据
                List<CereShopDiscountDetail> discountDetails = cereShopDiscountDetailService.findNumberDetails(cereShopOrder.getOrderId(), cereShopDiscount.getShopDiscountId());
                if (!EmptyUtils.isEmpty(discountDetails)) {
                    //更新redis限量库存
                    discountDetails.forEach(detail -> {
                        stringRedisService.set("限时折扣活动商品仅剩件数" + detail.getShopDiscountId() + detail.getSkuId(), detail.getNumber());
                    });
                    cereShopDiscountDetailService.updateBatch(discountDetails);
                }
            }
        }
        //更新库存数据
        List<CereProductSku> productSkus = cereProductSkuService.findStockNumberByOrderId(param.getOrderId());
        if (!EmptyUtils.isEmpty(productSkus)) {
            //更新商品库存数量
            for (CereProductSku sku : productSkus) {
                int stockNumber = cereProductSkuService.findStockNumberBySkuId(sku.getSkuId());
                if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                    stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                }
                sku.setStockNumber(stockNumber + sku.getStockNumber());
                //更新redis商品库存
                stringRedisService.set(String.valueOf(sku.getSkuId()), sku.getStockNumber());
            }
            cereProductSkuService.updateBatchSkus(productSkus);
        }
        //删除自动确认收货延时任务
        stringRedisService.delete(StringEnum.ORDER_CONFIRM_DILEVERY.getCode() + "-" + param.getOrderId());
        cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_CONFIRM_DILEVERY.getCode() + "-" + param.getOrderId());
        if (IntegerEnum.ORDER_STAY_DILEVERY.getCode().equals(cereShopOrder.getState())
                || IntegerEnum.YES.getCode().equals(cereShopOrder.getPaymentState())) {
            //如果是待发货或者待成团（且付款）取消,需要退款,查询支付流水数据
            CerePayLog refund = cereShopOrderDAO.findPayLog(cereShopOrder.getOrderFormid());
            if (refund != null) {
                //微信支付没通,暂时直接处理业务
//                handleRefundTestWxLog(order.getOrderFormid(),refund.getTransactionId(),refund.getOutTradeNo());
                Map<String, String> resultMap = wxPayService.orderRefund(refund.getTransactionId(), refund.getOutRefundNo(), refund.getTotalFee(), cereShopOrder.getPrice());
                if (!EmptyUtils.isEmpty(resultMap)) {
                    if (resultMap.get("return_msg").equals(WxPayEnum.REFUND_SUCCESS.getCode()) &&
                            resultMap.get("return_code").equals(WxPayEnum.REFUND_OK.getCode())) {
                        //退款成功
                    } else if (resultMap.get("return_code").equals(WxPayEnum.BUSINESS_BALANCE_NOTENOUGH.getCode())) {
                        //退款失败,商户余额不足
                        throw new CoBusinessException(CoReturnFormat.BUSINESS_BALANCE_NOT);
                    }
                }
            }
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void cancelBatch(List<Long> ids) throws CoBusinessException, Exception {
        String time = TimeUtils.yyMMddHHmmss();
        //查询订单信息
        List<CereShopOrder> orders = cereShopOrderDAO.findByIds(ids);
        for (CereShopOrder order : orders) {
            //修改订单状态为已取消
            order.setUpdateTime(time);
            order.setState(IntegerEnum.ORDER_STOP.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);
            //todo 修改退款状态
            cereShopOrderDAO.updateByOrderId(order.getOrderId());
            if (!EmptyUtils.isEmpty(order.getShopSeckillId())) {
                //查询秒杀活动数据
                CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(order.getShopSeckillId());
                if (IntegerEnum.YES.getCode().equals(cereShopSeckill.getIfNumber())) {
                    //如果限量,需要更新限量库存数据
                    List<CereShopSeckillDetail> seckillDetails = cereShopSeckillDetailService.findNumberDetails(order.getOrderId(), cereShopSeckill.getShopSeckillId());
                    if (!EmptyUtils.isEmpty(seckillDetails)) {
                        //更新redis限量库存
                        seckillDetails.forEach(detail -> {
                            stringRedisService.set("秒杀活动商品仅剩件数" + detail.getShopSeckillId() + detail.getSkuId(), detail.getNumber());
                        });
                        cereShopSeckillDetailService.updateBatch(seckillDetails);
                    }
                }
            }
            if (!EmptyUtils.isEmpty(order.getShopDiscountId())) {
                //查询秒杀活动数据
                CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(order.getShopDiscountId());
                if (IntegerEnum.YES.getCode().equals(cereShopDiscount.getIfNumber())) {
                    //如果限量,需要更新限量库存数据
                    List<CereShopDiscountDetail> discountDetails = cereShopDiscountDetailService.findNumberDetails(order.getOrderId(), cereShopDiscount.getShopDiscountId());
                    if (!EmptyUtils.isEmpty(discountDetails)) {
                        //更新redis限量库存
                        discountDetails.forEach(detail -> {
                            stringRedisService.set("限时折扣活动商品仅剩件数" + detail.getShopDiscountId() + detail.getSkuId(), detail.getNumber());
                        });
                        cereShopDiscountDetailService.updateBatch(discountDetails);
                    }
                }
            }
            //更新库存数据
            List<CereProductSku> productSkus = cereProductSkuService.findStockNumberByOrderId(order.getOrderId());
            if (!EmptyUtils.isEmpty(productSkus)) {
                //更新库存数量
                productSkus.forEach(sku -> {
                    int stockNumber = cereProductSkuService.findStockNumberBySkuId(sku.getSkuId());
                    if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                        stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                    }
                    sku.setStockNumber(stockNumber + sku.getStockNumber());
                    //更新redis商品库存
                    stringRedisService.set(String.valueOf(sku.getSkuId()), sku.getStockNumber());
                });
                cereProductSkuService.updateBatchSkus(productSkus);
            }
            if (IntegerEnum.YES.getCode().equals(order.getPaymentState())) {
                //如果付款了,需要退款,查询支付流水数据
                CerePayLog refund = cereShopOrderDAO.findPayLog(order.getOrderFormid());
                if (refund != null) {
                    //微信支付没通,暂时直接处理业务
//                    handleRefundTestWxLog(order.getOrderFormid(),refund.getTransactionId(),refund.getOutTradeNo());
                    Map<String, String> resultMap = wxPayService.orderRefund(refund.getTransactionId(), refund.getOutRefundNo(), refund.getTotalFee(), order.getPrice());
                    if (!EmptyUtils.isEmpty(resultMap)) {
                        if (resultMap.get("return_msg").equals(WxPayEnum.REFUND_SUCCESS.getCode()) &&
                                resultMap.get("return_code").equals(WxPayEnum.REFUND_OK.getCode())) {
                            //退款成功
                        } else if (resultMap.get("return_code").equals(WxPayEnum.BUSINESS_BALANCE_NOTENOUGH.getCode())) {
                            //退款失败,商户余额不足
                            throw new CoBusinessException(CoReturnFormat.BUSINESS_BALANCE_NOT);
                        }
                    }
                }
            }
            //新增订单关闭消息
            CereNotice cereNotice = new CereNotice();
            cereNotice.setNoticeType(IntegerEnum.NOTICE_TYPE_SYSTEM.getCode());
            cereNotice.setJump(IntegerEnum.NOTICE_JUMP_ORDER.getCode());
            cereNotice.setBuyerUserId(order.getBuyerUserId());
            cereNotice.setShopId(order.getShopId());
            cereNotice.setNoticeTitle(StringEnum.NOTICE_TITLE_ORDER_CANCEL.getCode());
            cereNotice.setNoticeContent("您未在规定时间完成付款，订单" + order.getOrderFormid() + "已关闭,点击查看详情");
            cereNotice.setOnly(order.getOrderId());
            cereNotice.setCreateTime(time);
            cereNotice.setIfRead(IntegerEnum.NO.getCode());
            cereNoticeService.insert(cereNotice);
        }
    }

    @Override
    public CereShopOrder findById(Long orderId) {
        return cereShopOrderDAO.selectByPrimaryKey(orderId);
    }

    @Override
    public void updateBuyerData(Long buyerUserId, Long id) throws CoBusinessException {
        cereShopOrderDAO.updateBuyerData(buyerUserId, id);
    }

    @Override
    public CereShopCouponRecording deleteByCouponCode(Long orderId, String token) {
        CerePlatformBusiness cerePlatformBusiness = cerePlatformBusinessDAO.selectByToken(token);
        //查询数据
        CereShopOrder cereShopOrder = cereShopOrderDAO.selectByPrimaryKey(orderId);
        CereOrderProduct cereShopProduct = cereOrderProductService.selectByOrderId(orderId);
        //修改状态
        cereShopOrderDAO.deleteCouponCode(orderId);
        //如果你不收货, 但是核销了码, 就把商品订单变成已收货
        cereShopOrderDAO.deleteCouponCode2(orderId);
        //实体类
        CereShopCouponRecording cereShopCouponRecording = new CereShopCouponRecording();

        //补填数据
        cereShopCouponRecording.setCouponCode(cereShopOrder.getCouponCode());
        SimpleDateFormat setCreateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = setCreateTime.format(new Date());
        cereShopCouponRecording.setCreateTime(format);
        cereShopCouponRecording.setProductPrice(cereShopOrder.getPrice());
        cereShopCouponRecording.setProductId(cereShopProduct.getProductId());
        cereShopCouponRecording.setProductName(cereShopProduct.getProductName());
        cereShopCouponRecording.setBusinessUserId(cerePlatformBusiness.getBusinessUserId());
        cereShopCouponRecording.setName(cerePlatformBusiness.getName());
        cereShopCouponRecording.setOrderId(orderId);
        cereShopCouponRecording.setIsUse(2);
        //插入数据
        cereShopCouponRecordingDao.insertSelective(cereShopCouponRecording);
//        //删除订单商品属性数据
//        cereShopOrderDAO.deleteOrderProductSkus(orderId);
//        //先删ticket_info
//        cereShopOrderDAO.deleteByticket(orderId);
//        //删除订单关联所有数据
//        cereShopOrderDAO.deleteAll(orderId);
        return cereShopCouponRecording;

    }

    @Override
    public CereShopOrder selectBycouponCode(String couponCode) {
        return cereShopOrderDAO.selectBycouponCode(couponCode);
    }

    @Override
    public List<CereShopCouponRecording> getOWritOff(Map map) {
        List<CereShopCouponRecording> list = cereShopCouponRecordingDao.list(map);
        for (CereShopCouponRecording cereShopCouponRecording : list) {
            cereShopCouponRecording.setIsUse(2);
        }

        return list;
    }

    @Override
    public List<Long> getOrderId() {
        return cereShopOrderDAO.getOrderId();
    }

    @Override
    public void updateState2(List<Long> ids) {
        cereShopOrderDAO.updateState2(ids);
    }

    @Override
    public void updateByOrderId(Long orderId) {
        cereShopOrderDAO.updateByOrderId(orderId);
    }


    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void addComment(CommentSaveParam commentParam, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        if (!EmptyUtils.isEmpty(commentParam.getParams())) {
            for (OrderCommentParam param : commentParam.getParams()) {
                //查询店铺数据
                CereShopComment cereShopComment = cereShopCommentService.findShop(param.getProductId());
                if (cereShopComment != null) {
                    cereShopComment.setBuyerUserId(user.getBuyerUserId());
                    cereShopComment.setCreateTime(time);
                    cereShopComment.setUpdateTime(time);
                    cereShopComment.setComment(param.getComment());
                    cereShopComment.setImage(param.getImage());
                    cereShopComment.setState(IntegerEnum.NO.getCode());
                    cereShopComment.setIfSensitive(IntegerEnum.NO.getCode());
                    cereShopComment.setOrderId(param.getOrderId());
                    cereShopComment.setSkuId(param.getSkuId());
                    cereShopComment.setStar(param.getStar());
                    cereShopComment.setDes(param.getDes());
                    cereShopComment.setDelivery(param.getDelivery());
                    cereShopComment.setAttitude(param.getAttitude());
                    cereShopComment.setImpression(param.getImpression());
                    //查询敏感词设置
                    CerePlatformSensitive sensitive = cerePlatformSensitiveService.findSensitive();
                    if (sensitive != null && IntegerEnum.YES.getCode().equals(sensitive.getState())) {
                        //校验是否存在敏感词
                        String[] split = sensitive.getSensitiveWord().split(",");
                        for (String word : split) {
                            if (param.getComment().contains(word)) {
                                //如果存在敏感词
                                if (IntegerEnum.SENSITIVE_STOP.getCode().equals(sensitive.getHandleMeasures())) {
                                    throw new CoBusinessException(CoReturnFormat.SENSITIVE_ERROR);
                                } else {
                                    //设置评论敏感词状态为需审核
                                    cereShopComment.setIfSensitive(IntegerEnum.YES.getCode());
                                }
                            }
                        }
                    }
                    try {
                        cereShopCommentService.insert(cereShopComment);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new CoBusinessException(CoReturnFormat.TOO_MANY_PICTURES);
                    }
                    //查询是否匹配关键词
                    List<CerePlatformWord> words = cereShopCommentService.findWords();
                    if (!EmptyUtils.isEmpty(words)) {
                        List<CereCommentWord> collect = words.stream()
                                .map(word -> {
                                    if (cereShopComment.getComment().contains(word.getKeyWord())) {
                                        CereCommentWord cereCommentWord = new CereCommentWord();
                                        cereCommentWord.setCommentId(cereShopComment.getCommentId());
                                        cereCommentWord.setProductId(cereShopComment.getProductId());
                                        cereCommentWord.setKeyWord(word.getKeyWord());
                                        cereCommentWord.setWordId(word.getWordId());
                                        return cereCommentWord;
                                    }
                                    return null;
                                }).filter(Objects::nonNull).collect(Collectors.toList());
                        if (!EmptyUtils.isEmpty(collect)) {
                            //批量插入关键词关联评论数据
                            cereCommentWordService.insertBatch(collect);
                        }
                    }
                }
            }
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void addToComment(CommentSaveParam saveParam, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        if (!EmptyUtils.isEmpty(saveParam.getParams())) {
            for (OrderCommentParam param : saveParam.getParams()) {
                //追加评论
                CereShopComment cereShopComment = new CereShopComment();
                cereShopComment.setCommentId(param.getCommentId());
                cereShopComment.setAddComment(param.getComment());
                cereShopComment.setAddImage(param.getImage());
                cereShopComment.setAddTime(time);
                cereShopComment.setUpdateTime(time);
                cereShopCommentService.update(cereShopComment);
            }
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void delete(OrderGetByIdParam param, CereBuyerUser user) throws CoBusinessException {

        //校验当前订单状态是否为已完成或者已取消
        CereShopOrder cereShopOrder = cereShopOrderDAO.checkStateFinishAndCancel(param.getOrderId());
        CereShopOrder cereShopOrder1 = cereShopOrderDAO.selectByPrimaryKey(param.getOrderId());
        //如果券码未使用则不让删除
        if (cereShopOrder1 != null && cereShopOrder1.getIsUse() != null) {
            if (cereShopOrder1.getIsUse().equals(1)) {
                throw new CoBusinessException(CoReturnFormat.CANNOT_DELETE_ORDER);
            }
        }

        if (cereShopOrder == null) {
            throw new CoBusinessException(CoReturnFormat.ORDER_NOT_TAKE);
        }
        //查询是否有售后数据
        List<CereOrderAfter> afters = cereShopOrderDAO.findAfterByOrderId(param.getOrderId());
        if (!EmptyUtils.isEmpty(afters)) {
            //删除售后商品属性数据
            cereShopOrderDAO.deleteAfterProductSkus(afters);
            //删除售后商品数据
            cereShopOrderDAO.deleteAfterProducts(afters);
        }
        //查询订单关联的所有消息id
        List<Long> noticeIds = cereNoticeService.findIdsByOrderId(param.getOrderId());
        if (!EmptyUtils.isEmpty(noticeIds)) {
            //删除消息数据
            cereNoticeService.deleteByIds(noticeIds);
            //删除客户关联消息数据
            cereNoticeService.deleteBuyerNotice(noticeIds, user.getBuyerUserId());
        }
        //删除订单商品属性数据
        cereShopOrderDAO.deleteOrderProductSkus(param.getOrderId());
        //先删ticket_info
        cereShopOrderDAO.deleteByticket(param.getOrderId());
        //删除订单关联所有数据
        cereShopOrderDAO.deleteAll(param.getOrderId());
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void returnExpress(CereAfterDilever dilever, CereBuyerUser user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        dilever.setCreateTime(time);
        cereAfterDileverService.insert(dilever);
        //修改售后单状态为退货中
        CereOrderAfter cereOrderAfter = new CereOrderAfter();
        cereOrderAfter.setAfterId(dilever.getAfterId());
        cereOrderAfter.setAfterState(IntegerEnum.AFTER_RETURN_STAY.getCode());
        cereOrderAfter.setUpdateTime(time);
        cereOrderAfterService.update(cereOrderAfter);
        //新增日志
        cerePlatformLogService.addLog(user, "售后管理", "客户端操作", "填写退货物流信息", dilever.getAfterId(), time);
    }

    @Override
    public List<Dilevery> getDilevery(DileveryParam param) throws CoBusinessException, Exception {
        List<Dilevery> list = new ArrayList<>();
        //查询物流查询策略
        Integer express = cerePlatformExpressService.findExpress();
        String code = "";
        if (IntegerEnum.EXPRESS_100.getCode().equals(express)) {
            //查询快递公司编码
            code = cerePlatformDictService.findByCompany(param.getExpress(), LongEnum.EXPRESS_100.getCode());
            //通过快递100查询物流轨迹
            List<ShippingTrace> traces = kuaiDi100Service.findTraces(code, param.getDeliverFormid());
            if (!EmptyUtils.isEmpty(traces)) {
                list = traces.stream()
                        .map(a -> {
                            Dilevery dilevery = new Dilevery();
                            dilevery.setReason(a.getAcceptStation());
                            dilevery.setTime(a.getAcceptTime());
                            return dilevery;
                        }).collect(Collectors.toList());
            }
        } else if (IntegerEnum.EXPRESS_NIAO.getCode().equals(express)) {
            //查询快递公司编码
            code = cerePlatformDictService.findByCompany(param.getExpress(), LongEnum.EXPRESS_NIAO.getCode());
            //通过快递鸟查询物流轨迹
            List<Object> traces = kuaiDiNiaoService.findTraces(code, param.getDeliverFormid());
        }
        return list;
    }

    @Override
    public void updateBatchStock(List<CereProductSku> skus) throws CoBusinessException {
        cereShopOrderDAO.updateBatchStock(skus);
    }

    private void addPayLog(CereShopOrder order, String time, String orderNo, String transactionId) throws Exception {
        CerePayLog payLog = new CerePayLog();
        payLog.setCreateTime(time);
        payLog.setOrderFormid(order.getOrderFormid());
        payLog.setOutTradeNo(orderNo);
        //设置退款单号
        if (orderNo.contains("XCX")) {
            //小程序支付
            payLog.setOutRefundNo("XCXTK" + TimeUtils.todayTime() + order.getOrderFormid() + order.getBuyerUserId());
        } else if (orderNo.contains("APP")) {
            //APP支付
            payLog.setOutRefundNo("APPTK" + TimeUtils.todayTime() + order.getOrderFormid() + order.getBuyerUserId());
        }
        payLog.setTransactionId(transactionId);
        payLog.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
        payLog.setShopId(order.getShopId());
        payLog.setState(StringEnum.PAY_LOG_PAY.getCode());
        payLog.setTotalFee(order.getPrice());
        payLog.setUserId(String.valueOf(order.getBuyerUserId()));
        payLog.setRemark(order.getCustomerName() + "使用微信支付了" + order.getPrice() + "元,支付订单号为：" + order.getOrderFormid()
                + ",支付时间为" + time);
        cerePayLogService.insert(payLog);
    }

    private void addReconciliation(CereShopOrder order, String time) throws Exception {
        CereOrderReconciliation reconciliation = new CereOrderReconciliation();
        reconciliation.setCreateTime(time);
        reconciliation.setMoney(order.getPrice());
        reconciliation.setOrderId(order.getOrderId());
        reconciliation.setState(IntegerEnum.RELATIONSHIP_FROZEN.getCode());
        reconciliation.setType(IntegerEnum.RELATIONSHIP_INCOME.getCode());
        cereOrderReconciliationService.insert(reconciliation);
    }

//    public static void main(String[] args) {
//        BigDecimal divide = new BigDecimal(10).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
//        BigDecimal bigDecimal = new BigDecimal(0.1).multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP);
//        System.out.println(bigDecimal);
//    }

    private void addDistributor(ShopDistributor distributor, CereShopOrder order, String time, List<CereDistributionOrder> distributionOrders) throws Exception {
//...yf根据商品序号查询该商品的分佣比例是多少，如果没有设置分佣比例，则默认用分销员的
        CereShopOrder shopOrder = cereShopOrderDAO.selectByPrimaryKey2(order.getOrderId());
        CereShopProduct cereShopProduct = cereShopProductDAO.selectByPrimaryKey(        shopOrder.getProductId());
        Integer commodityProportion = cereShopProduct.getCommodityProportion();
        if(commodityProportion == null ){
            commodityProportion = 0;
        }
        if (distributor.getIfLiquidation() != 0) {
            throw new CoBusinessException(CoReturnFormat.DISTRIBUTOR_WAS_DISCHARGED);
        }
        BigDecimal hundred = new BigDecimal(100);
//        if (!EmptyUtils.isEmpty(distributor.getDirectProportion())) {
        BigDecimal divide = new BigDecimal(0);
        if (commodityProportion != 0) {
            divide = new BigDecimal(commodityProportion).divide(hundred, 2, BigDecimal.ROUND_HALF_UP);
        }
//            else {
////                divide = new BigDecimal(distributor.getDirectProportion()).divide(hundred, 2, BigDecimal.ROUND_HALF_UP);
//            }
        //计算直接分佣佣金=订单金额*直接分佣比例
//            BigDecimal divide = new BigDecimal(distributor.getDirectProportion()).divide(hundred, 2, BigDecimal.ROUND_HALF_UP);
        order.setDirectDistributorMoney(order.getPrice().multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP));
        //新增直接分销订单
        CereDistributionOrder distributionOrder = new CereDistributionOrder();
        distributionOrder.setOrderId(order.getOrderId());
        distributionOrder.setOrderFormid(order.getOrderFormid());
        distributionOrder.setDistributorName(distributor.getDistributorName());
        distributionOrder.setDistributorPhone(distributor.getDistributorPhone());
        distributionOrder.setPrice(order.getPrice());
        distributionOrder.setCommission(order.getDirectDistributorMoney());
        distributionOrder.setDistributorId(distributor.getDistributorId());
        distributionOrder.setState(IntegerEnum.NO.getCode());
        distributionOrder.setTransactionTime(time);
        distributionOrder.setType(IntegerEnum.DIRECT_TYPE.getCode());
        distributionOrders.add(distributionOrder);

        //添加获得佣金记录
        CereShopCommissionRecord record = new CereShopCommissionRecord();
        record.setOrederId(order.getOrderId());
        record.setDetail(incomeDetail);
        record.setCommission(order.getDirectDistributorMoney());
        record.setState(1);
        record.setDistributorId(distributor.getDistributorId());
        record.setCreateTime(time);
        cereShopCouponRecordingsService.insertSelective(record);
//        }
        //间接分佣
//        if (!EmptyUtils.isEmpty(distributor.getInvitees()) && !EmptyUtils.isEmpty(distributor.getIndirectProportion())) {
//            //计算间接分佣佣金=订单金额*间接分佣比例
//            BigDecimal divide = new BigDecimal(distributor.getIndirectProportion()).divide(hundred, 2, BigDecimal.ROUND_HALF_UP);
//            order.setIndirectDistributorMoney(order.getPrice().multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP));
//            //新增间接分佣订单
//            CereDistributionOrder distributionOrder = new CereDistributionOrder();
//            distributionOrder.setCommission(order.getIndirectDistributorMoney());
//            distributionOrder.setDistributorId(distributor.getInvitees());
//            distributionOrder.setDistributorName(distributor.getInviteesName());
//            distributionOrder.setDistributorPhone(distributor.getInviteesPhone());
//            distributionOrder.setOrderFormid(order.getOrderFormid());
//            distributionOrder.setOrderId(order.getOrderId());
//            distributionOrder.setPrice(order.getPrice());
//            distributionOrder.setState(IntegerEnum.NO.getCode());
//            distributionOrder.setType(IntegerEnum.IN_DIRECT_TYPE.getCode());
//            distributionOrder.setTransactionTime(time);
//            distributionOrders.add(distributionOrder);
//        }
    }

    private void addOrder(PayUrl payUrl, Long parentId, OrderParam param, CereBuyerUser user, String time,
                          Map<Long, CartSku> map, CereBuyerCoupon buyerCoupon, Map<Long, CereBuyerShopCoupon> discountMap, CereShopTicketInfo ticketInfo) throws CoBusinessException, Exception {
        //遍历店铺
        List<CartSku> carts = new ArrayList<>();
        List<CartSku> skus = null;
        if (!EmptyUtils.isEmpty(map)) {
            //拿到所有商品数据
            skus = map.keySet().stream().map(map::get).collect(Collectors.toList());
        }
        //查询所有规格属性数据
        List<OrderProductAttribute> attributes = cereOrderProductAttributeService.findBySkus(skus);
        //查询收货地址数据
        CereBuyerReceive receive = cereBuyerReceiveService.findById(param.getReceiveId());
//        if(receive!=null){
        for (OrderProductParam shop : param.getShops()) {
            //封装子订单数据
            CereShopOrder order = new CereShopOrder();
            CereShopProduct cereShopProduct = cereShopProductService.selectByPrimaryKey(skus.get(0).getProductId());
            order.setShopId(shop.getShopId());
            order.setParentId(parentId);
            order.setBuyerUserId(user.getBuyerUserId());
            order.setCreateTime(time);
            order.setUpdateTime(time);
            order.setCouponId(param.getCouponId());
            if (receive != null) {
                order.setReceiveName(receive.getReceiveName());
                order.setReceivePhone(receive.getReceivePhone());
                order.setReceiveAdress(receive.getReceiveAdress());
                order.setAddress(receive.getAddress());
            }
            order.setCustomerName(user.getWechatName());
            order.setCustomerPhone(user.getPhone());
            order.setLogisticsPrice(shop.getDistribution().getDistributionPrice());
            order.setLogisticsId(shop.getDistribution().getLogisticsId());
            order.setState(IntegerEnum.ORDER_STAY_PAY.getCode());
            order.setOrderFormid(RandomStringUtil.getRandomCode(15, 0));
            //定义订单优惠券金额（平台优惠金额/店铺总数+店铺优惠金额）
            BigDecimal discountPrice = new BigDecimal(0);
            if (buyerCoupon != null) {
                discountPrice = buyerCoupon.getReduceMoney().divide(
                        new BigDecimal(param.getShops().size()), 2, BigDecimal.ROUND_HALF_UP);
                //更新平台优惠券状态为已使用
                buyerCoupon.setUpdateTime(time);
                buyerCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                cereBuyerCouponService.updateState(buyerCoupon);
                //删除redis延时任务
                stringRedisService.delete(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                        + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                //删除redis记录数据
                cereRedisKeyServcice.deleteByKey(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                        + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
            }
            //计算订单优惠金额
            if (!EmptyUtils.isEmpty(shop.getId()) && !EmptyUtils.isEmpty(discountMap)) {
                order.setId(shop.getId());
                if (!EmptyUtils.isEmpty(discountMap.get(shop.getId()))) {
                    CereBuyerShopCoupon cereBuyerShopCoupon = discountMap.get(shop.getId());
                    //更新店铺优惠券状态为已使用
                    cereBuyerShopCoupon.setUpdateTime(time);
                    cereBuyerShopCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                    cereBuyerShopCouponService.updateState(cereBuyerShopCoupon);
                    //删除redis延时任务
                    stringRedisService.delete(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                    cereRedisKeyServcice.deleteByKey(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                    order.setShopOperateId(cereBuyerShopCoupon.getShopOperateId());
                    if (!EmptyUtils.isEmptyBigdecimal(discountPrice)) {
                        discountPrice = discountPrice.add(cereBuyerShopCoupon.getReduceMoney());
                    } else {
                        discountPrice = cereBuyerShopCoupon.getReduceMoney();
                    }
                }
            }
            order.setDiscountPrice(discountPrice);
            if (!EmptyUtils.isEmpty(skus)) {
                //定义店铺商品总金额字段
                final BigDecimal[] total = {new BigDecimal(0)};
                //设置规格数量
                skus.forEach(sku -> {
                    if (sku.getShopId().equals(shop.getShopId())) {
                        total[0] = total[0].add(sku.getPrice().multiply(
                                new BigDecimal(sku.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                });
                //订单总金额=店铺商品总金额+运费
                order.setOrderPrice(total[0].add(order.getLogisticsPrice()));
                //订单支付金额=订单总金额-优惠
                order.setPrice(order.getOrderPrice().subtract(order.getDiscountPrice()));
                order.setPaymentState(IntegerEnum.ORDER_PAY_STAY.getCode());
                order.setPaymentMode(IntegerEnum.ORDER_PAY_WX.getCode());
                order.setRemark(param.getRemark());
                order.setBuyerUserId(user.getBuyerUserId());
                Long classifyId = cereShopProduct.getClassifyId();
                if (classifyId == 7) {
                    order.setPaymentTime(order.getCreateTime());
                }
                payUrl.setOrderFormid(order.getOrderFormid());
                //添加分享人id
                order.setSharerId(param.getBuyerUserId());
                //插入订单数据
                cereShopOrderDAO.insert(order);

                //新增订单商品数据
                addOrderProduct(skus, order.getOrderId(), shop.getShopId(), map, carts, attributes);
                //插入新增订单附属数据(新增订单附属数据)
                if (!EmptyUtils.isEmpty(ticketInfo.getCustomer()) && !EmptyUtils.isEmpty(order.getOrderId())) {
                    List<CereOrderProduct> cereOrderProductByOrderId = dlCereOrderProductDao.findCereOrderProductByOrderId(order.getOrderId());
                    CereOrderProduct cereOrderProduct = cereOrderProductByOrderId.get(0);
                    CereShopProduct cereShopProductByProductId = dlCereOrderProductDao.findCereShopProductByProductId(cereOrderProduct.getProductId());
                    Integer number = 0;
                    BigDecimal price = new BigDecimal(0L);
                    for (CartSku cartSku : skus) {
                         number = cartSku.getNumber();
                         price = cartSku.getPrice();
                    }
                    //.如果ticketInfo不为空则代表是助销客票务，使用校验接口校验票务是否能够购买
                    OrderValidation orderValidation = new OrderValidation();
                    //.合作方订单流水号
                    orderValidation.setOrderSerialId(order.getOrderFormid());
                    //.平台产品编号
                    orderValidation.setProductNo(cereShopProductByProductId.getProductNo());
                    //.	支付方式(0 景区到付 1 在线支付)
                    orderValidation.setPayType(1);
                    //.	预订数量
                    orderValidation.setTickets(number);
                    //.协议价格，单位分
                    orderValidation.setContractPrice(price.longValue());
                    //.预订人姓名
                    orderValidation.setBookName(ticketInfo.getCustomer());
                    //.实际预订单价，单位分
                    orderValidation.setPrice(price.longValue());
                    //.预订人手机号
                    orderValidation.setBookMobile(ticketInfo.getCustomerTel());
                    //.身份证号(根据产品实名制信息传入)
                    orderValidation.setIdCard(ticketInfo.getCustomerCard());
                    //.游玩日期(yyyy-MM-dd)
                    orderValidation.setTravelDate(ticketInfo.getTravelDate());
                    //.预定开始时间(HH:mm:ss)
                    orderValidation.setBookBeginTime(null);
                    //.预定结束时间(HH:mm:ss)
                    orderValidation.setBookEndTime(null);
                    JSONObject verifyOrder = sendPost.VerifyOrder(orderValidation);
                    String resCode = (String) verifyOrder.get("res_code");
                    if (!resCode.equals(PI)){
                        String resMsg = (String) verifyOrder.get("res_msg");
                        throw new CoBusinessException(resMsg);
                    }else {
                        ticketInfo.setOrderId(order.getOrderId());
                        cereShopOrderDAO.insertTicketInfo(ticketInfo);
                    }
                }

                //YF.下单的时候需要进行判断(市民票只能购买一张)
                //YF.根据订单号查询订单商品信息表，查询到该商品的productNo,判断是否为yml配置的市民票，如果是市民票，则再进行判断是否搜索到了重复的订单，如果大于1则不让他购买
//                CereShopProduct cereShopProduct1 = null;
//                List<CereOrderProduct> cereOrderProductByOrderId = dlCereOrderProductDao.findCereOrderProductByOrderId(order.getOrderId());
//                CereOrderProduct cereOrderProduct = cereOrderProductByOrderId.get(0);
//                if (cereOrderProduct != null) {
//                    cereShopProduct1 = dlCereOrderProductDao.findCereShopProductByProductId(cereOrderProduct.getProductId());
//                }
//                List<CereShopTicketInfo> cereShopTicketInfoBycustomerCard = dlCereOrderProductDao.findCereShopTicketInfoBycustomerCard(param.getIdCard());
//                for (CereShopTicketInfo cereShopTicketInfo : cereShopTicketInfoBycustomerCard) {
//                    OrderDetail detail = cereShopOrderDAO.getById(cereShopTicketInfo.getOrderId());
//                    if (detail.getState().equals(3) || detail.getState().equals(4)) {
//                        //.如果是市民票，则再进行查询，订单是否唯一,根据订单号，身份证查询
//                        if (cereShopProduct1.getProductNo().equals(productNoCard)) {
//                            if (dlCereOrderProductDao.findCereShopTicketInfoBycustomerCardCount(param.getIdCard()) > countCustomerCard) {
//                                throw new CoBusinessException("亲,您不能下单，一张身份证只能购买规定数量的产品哦");
//                            }
//                        }
//                    }
//                }
                //.YF写到这里
                //设置30分钟延时自动取消订单,并且释放库存
                stringRedisService.set(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), param.getShops(), 30 * 60 * 1000);
                //新增延时任务记录
                cereRedisKeyServcice.add(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), TimeUtils.getMinuteAfter(30));
                //如果是积分商品,就直接推送
                if(classifyId == 7){
                    //推送通信
                    websocket.sendMessage(order.getShopId(), "1");
                }
            }
        }
        //批量更新库存数量
        cereProductSkuService.updateBatch(skus);

        //插入规格属性数据
        if (!EmptyUtils.isEmpty(attributes)) {
            cereOrderProductAttributeService.insertBatch(attributes);
        }
//    }
        if (!EmptyUtils.isEmpty(carts)) {
            //删除购物车商品
            cereShopCartService.deleteSkus(carts, user.getBuyerUserId());
        }
    }

    private void addOrderProduct(List<CartSku> skus, Long orderId, Long shopId,
                                 Map<Long, CartSku> map, List<CartSku> carts, List<OrderProductAttribute> attributes) throws CoBusinessException {
        if (!EmptyUtils.isEmpty(skus)) {
            for (CartSku sku : skus) {
                if (sku.getShopId().equals(shopId)) {
                    if (IntegerEnum.YES.getCode().equals(sku.getSelected())) {
                        //购物车商品,需要删除
                        carts.add(sku);
                    }
                    CereOrderProduct orderProduct = new CereOrderProduct();
                    orderProduct.setOrderId(orderId);
                    orderProduct.setProductId(sku.getProductId());
                    orderProduct.setSkuId(sku.getSkuId());
                    orderProduct.setImage(sku.getImage());
                    orderProduct.setNumber(sku.getNumber());
                    orderProduct.setProductName(sku.getProductName());
                    orderProduct.setProductPrice(sku.getPrice());
                    orderProduct.setSKU(sku.getSKU());
                    orderProduct.setWeight(sku.getWeight());
                    orderProduct.setAvailable(sku.getNumber());
                    //插入订单商品明细数据
                    cereOrderProductService.insert(orderProduct);
                    //更新库存数量
                    int stockNumber = 0;
                    if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                        stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                    } else {
                        stockNumber = map.get(sku.getSkuId()).getStockNumber();
                    }
                    sku.setStockNumber(stockNumber - sku.getNumber());
                    //更新redis商品库存
                    stringRedisService.set(String.valueOf(sku.getSkuId()), stockNumber - sku.getNumber());
                    //根据规格id查询规格属性数据
                    if (!EmptyUtils.isEmpty(attributes)) {
                        attributes.forEach(a -> {
                            if (sku.getSkuId().equals(a.getSkuId())) {
                                a.setOrderProductId(orderProduct.getOrderProductId());
                            }
                        });
                    }
                }
            }
        }
    }


    private void shopCart(Settlement settlement, SettlementParam param, CereBuyerUser user, List<ProductCoupon> coupons) throws CoBusinessException {
        //定义是否提示
        AtomicBoolean flag = new AtomicBoolean(false);
        //封装商品明细数据
        if (!EmptyUtils.isEmpty(param.getShops())) {
            List<SettlementShop> invalidShops = new ArrayList<>();
            List<SettlementShop> collect = new ArrayList<>();
            for (ShopProductParam shop : param.getShops()) {
                //查询店铺信息
                SettlementShop settlementShop = cereShopOrderDAO.findSettlementShop(shop.getShopId());
                settlementShop.setShopId(shop.getShopId());
                List<CartSku> invalidSkus = new ArrayList<>();
                int invalidNumber = 0;
                BigDecimal total = new BigDecimal(0);
                Map<Long, CartSku> map = new HashMap<>();
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    //查询当前店铺所有购买商品的库存数据
                    List<CartSku> productSkus = cereProductSkuService.findStockNumberBySkus(shop.getSkus());
                    if (!EmptyUtils.isEmpty(productSkus)) {
                        productSkus.forEach(sku -> {
                            map.put(sku.getSkuId(), sku);
                        });
                    }
                    Map<Long, CartSku> finalMap = map;
                    //将商品数量放到map中
                    Map<Long, Integer> numberMap = shop.getSkus().stream()
                            .collect(Collectors.toMap(ProductSku::getSkuId, ProductSku::getNumber));
                    if (!EmptyUtils.isEmpty(numberMap)) {
                        //查询规格信息数据
                        List<CartSku> skus = cereProductSkuService.findSkuBySkus(shop.getSkus());
                        if (!EmptyUtils.isEmpty(skus)) {
                            for (CartSku sku : skus) {
                                //秒杀活动和限时折扣活动校验
                                checkActivity(param, numberMap.get(sku.getSkuId()), sku, settlement, user, shop);
                                //设置规格属性值数组
                                sku.setValues(EmptyUtils.getImages(sku.getValue()));
                                sku.setNumber(numberMap.get(sku.getSkuId()));
                                sku.setTotal(new BigDecimal(sku.getNumber()).multiply(sku.getPrice()));
                                sku.setSelected(IntegerEnum.YES.getCode());
                                //定义是否需要查询优惠券标识,默认需要
                                setSettlementCoupons(param, user.getBuyerUserId(), sku, settlementShop, settlement,
                                        settlement.getCoupons(), settlementShop.getShopCoupons());
                                //校验库存
                                int stockNumber = 0;
                                if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                    stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                                } else {
                                    stockNumber = finalMap.get(sku.getSkuId()).getStockNumber();
                                }
                                if (sku.getNumber() > stockNumber) {
                                    //叠加商品件数
                                    invalidNumber += sku.getNumber();
                                    flag.set(true);
                                    invalidSkus.add(sku);
                                }
                                total = total.add(sku.getTotal());
                            }
                            settlementShop.setSkus(skus);
                            settlementShop.setNumber(skus.stream().mapToInt(CartSku::getNumber).sum());
                            if (flag.get()) {
                                SettlementShop settlementShop1 = new SettlementShop();
                                settlementShop1.setShopId(shop.getShopId());
                                settlementShop1.setNumber(invalidNumber);
                                settlementShop1.setSkus(invalidSkus);
                                invalidShops.add(settlementShop1);
                            } else {
                                //查询店铺物流方案
                                List<CereOrderLogistics> logistics = cereOrderLogisticsService.findLogistics(shop.getShopId());
                                //计算物流费用
                                Distribution distribution = setLogisticPrice(logistics, skus, settlement.getReceive(), numberMap);
                                settlementShop.setDistribution(distribution);
                            }
                        }
                    }
                }
                settlementShop.setTotal(total);
                collect.add(settlementShop);
            }
            settlement.setShops(collect);
            settlement.setInvalidShops(invalidShops);
            if (flag.get()) {
                //超出库存,提示‘存在无效商品，请重新选择’
                //超出库存,提示‘库存不足,请重新选择INVENTORY_SHORTAGE’
                throw new CoBusinessException(CoReturnFormat.INVENTORY_SHORTAGE, settlement);
            }
        }
    }

    private void setSettlementCoupons(SettlementParam param, Long buyerUserId, CartSku sku,
                                      SettlementShop settlementShop, Settlement settlement,
                                      List<ProductCoupon> coupons, List<ProductCoupon> shopCoupons) {
        if (EmptyUtils.isEmpty(coupons)) {
            coupons = new ArrayList<>();
        }
        if (EmptyUtils.isEmpty(shopCoupons)) {
            shopCoupons = new ArrayList<>();
        }
        boolean flag = true;
        if (!EmptyUtils.isLongEmpty(param.getShopDiscountId()) || !EmptyUtils.isLongEmpty(param.getShopSeckillId())) {
            //营销活动购买
            if (!EmptyUtils.isLongEmpty(param.getShopDiscountId())) {
                //限时折扣活动购买,查询限时折扣活动数据
                CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(param.getShopDiscountId());
                if (IntegerEnum.NO.getCode().equals(cereShopDiscount.getIfAdd())) {
                    //不允许优惠叠加
                    flag = false;
                }
            } else if (!EmptyUtils.isLongEmpty(param.getShopSeckillId())) {
                //秒杀活动购买,查询秒杀活动数据
                CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(param.getShopSeckillId());
                if (IntegerEnum.NO.getCode().equals(cereShopSeckill.getIfAdd())) {
                    //允许优惠叠加
                    flag = false;
                }
            }
        }
        if (flag) {
            //根据商品id、商品价格查询满足条件的平台优惠券
            List<ProductCoupon> productCoupons = cereBuyerCouponService.findCouponByProduct(sku.getTotal(),
                    buyerUserId, sku.getProductId());
            //拼接活动id、满减金额字符串以便去重
            if (!EmptyUtils.isEmpty(productCoupons)) {
                List<ProductCoupon> finalCoupons = coupons;
                productCoupons.forEach(coupon -> {
                    coupon.setDistinct(coupon.getActivityId() + "-" + coupon.getFullMoney());
                    finalCoupons.add(coupon);
                });
            }
            if (!EmptyUtils.isEmpty(coupons)) {
                //去除重复活动和对应金额优惠券
                coupons = coupons.stream().collect(
                        Collectors.collectingAndThen(Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(data -> data.getDistinct()))), ArrayList::new)
                );
                if (!EmptyUtils.isEmpty(coupons)) {
                    //设置优惠券内容
                    coupons.forEach(tool -> {
                        tool.setContent("满" + tool.getFullMoney().stripTrailingZeros().toPlainString() +
                                "减" + tool.getReduceMoney().stripTrailingZeros().toPlainString() + "元");
                    });
                }
                settlement.setCoupons(coupons);
            }
            //查询店铺优惠券数据
            List<ProductCoupon> couponList = cereBuyerShopCouponService.findCouponByProduct(sku.getTotal(),
                    buyerUserId, sku.getProductId());
            if (!EmptyUtils.isEmpty(couponList)) {
                List<ProductCoupon> finalShopCoupons = shopCoupons;
                couponList.forEach(coupon -> {
                    if (IntegerEnum.COUPON_TYPE_DISCOUNT.getCode().equals(coupon.getCouponType())) {
                        //如果是折扣券,查询关联的所有商品id
                        coupon.setIds(cereBuyerShopCouponService.findProductIds(coupon.getShopCouponId()));
                        coupon.setContent(coupon.getReduceMoney().stripTrailingZeros().toPlainString() + "折券");
                    } else {
                        coupon.setContent("满" + coupon.getFullMoney().stripTrailingZeros().toPlainString() +
                                "减" + coupon.getReduceMoney().stripTrailingZeros().toPlainString() + "元");
                    }
                    finalShopCoupons.add(coupon);
                });
                //去除重复店铺优惠券
                shopCoupons = shopCoupons.stream().collect(
                        Collectors.collectingAndThen(Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(data -> data.getShopCouponId()))), ArrayList::new));
            }
            settlementShop.setShopCoupons(shopCoupons);
        }
    }

    private void buyNow(Settlement settlement, SettlementParam param, CereBuyerUser user, List<ProductCoupon> coupons) throws CoBusinessException {
        if (!EmptyUtils.isEmpty(param.getShops())) {
            List<SettlementShop> shops = new ArrayList<>();
            for (ShopProductParam shop : param.getShops()) {
                //新增转化数据
                CereShopConversion cereShopConversion = new CereShopConversion();
                cereShopConversion.setShopId(shop.getShopId());
                cereShopConversion.setCreateTime(TimeUtils.yyMMddHHmmss());
                cereShopConversion.setType(ParamEnum.CONVERSION_CHECK.getCode());
                cereShopConversionService.insert(cereShopConversion);
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    //将商品数量放到map中
                    Map<Long, Integer> map = shop.getSkus().stream()
                            .collect(Collectors.toMap(ProductSku::getSkuId, ProductSku::getNumber));
                    if (!EmptyUtils.isEmpty(map)) {
                        //封装商品明细数据
                        SettlementShop settlementShop = cereShopOrderDAO.findSettlementShop(shop.getShopId());
                        //查询规格信息数据
                        List<CartSku> skus;
                        if (IntegerEnum.YES.getCode().equals(param.getIfWork())) {
                            //拼团单独购买
                            skus = cereProductSkuService.findOriginalSkuBySkus(shop.getSkus());
                        } else {
                            skus = cereProductSkuService.findSkuBySkus(shop.getSkus());
                        }
                        if (!EmptyUtils.isEmpty(skus)) {
                            //查询店铺物流方案
                            List<CereOrderLogistics> logistics = cereOrderLogisticsService.findLogistics(shop.getShopId());
                            //计算物流费用
                            Distribution distribution = setLogisticPrice(logistics, skus, settlement.getReceive(), map);
                            settlementShop.setDistribution(distribution);
                            BigDecimal total = new BigDecimal(0);
                            for (CartSku sku : skus) {
                                //秒杀活动和限时折扣活动校验
                                checkActivity(param, map.get(sku.getSkuId()), sku, settlement, user, shop);
                                //设置规格属性值数组
                                sku.setValues(EmptyUtils.getImages(sku.getValue()));
                                if (settlementShop != null) {
                                    //设置商品数量
                                    sku.setNumber(map.get(sku.getSkuId()));
                                    //校验库存
                                    int stockNumber;
                                    if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                        stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                                    } else {
                                        stockNumber = cereProductSkuService.findStockNumberBySkuId(sku.getSkuId());
                                    }
                                    if (sku.getNumber() > stockNumber) {
                                        //超出库存,提示‘商品已不可售，看看其他的吧’
                                        throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
                                    }
                                    if (sku.getClassifyId().equals(Long.valueOf(7))) {
                                        sku.setPrice(sku.getPrice().multiply(BigDecimal.valueOf(exchangeRate)));
                                        //封装商品数据
                                        sku.setTotal(new BigDecimal(map.get(sku.getSkuId())).multiply(sku.getPrice()));

                                    } else {
                                        sku.setTotal(new BigDecimal(map.get(sku.getSkuId())).multiply(sku.getPrice()));
                                    }
                                    total = total.add(sku.getTotal());
                                    sku.setSelected(IntegerEnum.YES.getCode());
                                    //封装优惠券数据
                                    setSettlementCoupons(param, user.getBuyerUserId(), sku, settlementShop, settlement
                                            , settlement.getCoupons(), settlementShop.getShopCoupons());
                                }
                            }
                            settlementShop.setNumber(skus.stream().mapToInt(CartSku::getNumber).sum());
                            settlementShop.setSkus(skus);
                            settlementShop.setTotal(total);
                            settlementShop.setTotal(total);
                            shops.add(settlementShop);
                        }
                    }
                }
            }
            settlement.setShops(shops);
        }
    }

    /**
     * 结算接口校验
     */
    private void checkActivity(SettlementParam param, Integer number, CartSku sku, Settlement settlement,
                               CereBuyerUser user, ShopProductParam shop) throws CoBusinessException {
        List<ProductCoupon> coupons = null;
        Long skuId = sku.getSkuId();
        if (!EmptyUtils.isEmpty(param.getShopSeckillId()) || !EmptyUtils.isEmpty(shop.getShopSeckillId())) {
            Long shopSeckillId = param.getShopSeckillId();
            if (EmptyUtils.isEmpty(shopSeckillId)) {
                shopSeckillId = shop.getShopSeckillId();
            }
            //查询秒杀活动数据
            CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(shopSeckillId);
            if (cereShopSeckill != null) {
                //查询优惠券
                coupons = setCoupons(cereShopSeckill.getIfAdd(), sku, user);
                settlement.setCoupons(coupons);
                //定义加锁key
                String key = "秒杀活动商品仅剩件数" + cereShopSeckill.getShopSeckillId();
                //加锁
                RLock redissonLock = redisson.getLock(key);
                redissonLock.lock();
                if (IntegerEnum.PRODUCT_IF_LIMIT_YES.getCode().equals(cereShopSeckill.getIfLimit())) {
                    //如果秒杀活动限购,校验数量
                    if (number > cereShopSeckill.getLimitNumber()) {
                        throw new CoBusinessException(CoReturnFormat.PRODUCT_LIMIT_ERROR, redissonLock);
                    }
                }
                if (IntegerEnum.YES.getCode().equals(cereShopSeckill.getIfNumber())) {
                    int surplusNumber = 0;
                    //如果限量,查询缓存中活动商品仅剩数量
                    if (EmptyUtils.isEmpty(stringRedisService.get("秒杀活动商品仅剩件数" + cereShopSeckill.getShopSeckillId() + skuId))) {
                        //如果没有,取数据库限量库存数据
                        surplusNumber = cereShopSeckillDetailService.findNumber(cereShopSeckill.getShopSeckillId(), sku.getSkuId());
                    } else {
                        //如果有,取缓存
                        surplusNumber = (int) stringRedisService.get("秒杀活动商品仅剩件数" + cereShopSeckill.getShopSeckillId() + skuId);
                    }
                    //判断数量是否大于当前购买数量
                    if (number > surplusNumber) {
                        throw new CoBusinessException(CoReturnFormat.PRODUCT_ALREADY_SELL_OUT, redissonLock);
                    }
                }
                //解锁
                redissonLock.unlock();
            }
        }
        if (!EmptyUtils.isEmpty(param.getShopDiscountId()) || !EmptyUtils.isEmpty(shop.getShopDiscountId())) {
            Long shopDiscountId = param.getShopDiscountId();
            if (EmptyUtils.isEmpty(shopDiscountId)) {
                shopDiscountId = shop.getShopDiscountId();
            }
            //查询限时折扣活动数据
            CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(shopDiscountId);
            if (cereShopDiscount != null) {
                //查询优惠券
                coupons = setCoupons(cereShopDiscount.getIfAdd(), sku, user);
                settlement.setCoupons(coupons);
                //定义加锁key
                String key = "限时折扣活动商品仅剩件数" + cereShopDiscount.getShopDiscountId();
                //加锁
                RLock redissonLock = redisson.getLock(key);
                redissonLock.lock();
                if (IntegerEnum.PRODUCT_IF_LIMIT_YES.getCode().equals(cereShopDiscount.getIfLimit())) {
                    //如果限时折扣活动限购,校验数量
                    if (number > cereShopDiscount.getLimitNumber()) {
                        throw new CoBusinessException(CoReturnFormat.PRODUCT_LIMIT_ERROR, redissonLock);
                    }
                }
                if (IntegerEnum.YES.getCode().equals(cereShopDiscount.getIfNumber())) {
                    int surplusNumber = 0;
                    //如果限量,查询缓存中活动商品仅剩数量
                    if (EmptyUtils.isEmpty(stringRedisService.get("限时折扣活动商品仅剩件数" + cereShopDiscount.getShopDiscountId() + skuId))) {
                        //如果没有,取数据库限量库存数据
                        surplusNumber = cereShopDiscountDetailService.findNumber(cereShopDiscount.getShopDiscountId(), sku.getSkuId());
                    } else {
                        //如果有,取缓存
                        surplusNumber = (int) stringRedisService.get("限时折扣活动商品仅剩件数" + cereShopDiscount.getShopDiscountId() + skuId);
                    }
                    //判断数量是否大于当前购买数量
                    if (number > surplusNumber) {
                        throw new CoBusinessException(CoReturnFormat.PRODUCT_ALREADY_SELL_OUT, redissonLock);
                    }
                }
                //解锁
                redissonLock.unlock();
            }
        }
    }

    /**
     * 提交订单校验秒杀活动限量和限购
     */
    private void checkSeckillActivity(CereShopSeckill cereShopSeckill, Integer number, CartSku sku, List<CereShopSeckillDetail> seckillDetails) throws CoBusinessException {
        //定义加锁key
        String key = "秒杀活动商品仅剩件数" + cereShopSeckill.getShopSeckillId();
        //加锁
        RLock redissonLock = redisson.getLock(key);
        redissonLock.lock();
        if (IntegerEnum.PRODUCT_IF_LIMIT_YES.getCode().equals(cereShopSeckill.getIfLimit())) {
            //如果秒杀活动限购,校验数量
            if (number > cereShopSeckill.getLimitNumber()) {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_LIMIT_ERROR, redissonLock);
            }
        }
        if (IntegerEnum.YES.getCode().equals(cereShopSeckill.getIfNumber())) {
            int surplusNumber = 0;
            //如果限量,查询缓存中活动商品仅剩数量
            if (EmptyUtils.isEmpty(stringRedisService.get("秒杀活动商品仅剩件数" + cereShopSeckill.getShopSeckillId() + sku.getSkuId()))) {
                //如果缓存中没有,取数据库中仅剩件数
                surplusNumber = cereShopSeckillDetailService.findNumber(cereShopSeckill.getShopSeckillId(), sku.getSkuId());
            } else {
                //如果缓存中有,就使用缓存中仅剩件数
                surplusNumber = (int) stringRedisService.get("秒杀活动商品仅剩件数" + cereShopSeckill.getShopSeckillId() + sku.getSkuId());
            }
            //判断数量是否大于当前购买数量
            if (number > surplusNumber) {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_ALREADY_SELL_OUT, redissonLock);
            }
            //设置更新限量库存数据
            CereShopSeckillDetail detail = new CereShopSeckillDetail();
            detail.setShopSeckillId(cereShopSeckill.getShopSeckillId());
            detail.setSkuId(sku.getSkuId());
            detail.setNumber(surplusNumber - number);
            seckillDetails.add(detail);
        }
        //解锁
        redissonLock.unlock();
    }

    /**
     * 提交订单校验限时折扣限量和限购
     */
    private void checkDiscountActivity(CereShopDiscount cereShopDiscount, Integer number, CartSku sku, List<CereShopDiscountDetail> discountDetails) throws CoBusinessException {
        //定义加锁key
        String key = "限时折扣活动商品仅剩件数" + cereShopDiscount.getShopDiscountId();
        //加锁
        RLock redissonLock = redisson.getLock(key);
        redissonLock.lock();
        if (IntegerEnum.PRODUCT_IF_LIMIT_YES.getCode().equals(cereShopDiscount.getIfLimit())) {
            //如果限时折扣活动限购,校验数量
            if (number > cereShopDiscount.getLimitNumber()) {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_LIMIT_ERROR, redissonLock);
            }
        }
        if (IntegerEnum.YES.getCode().equals(cereShopDiscount.getIfNumber())) {
            int surplusNumber = 0;
            //如果限量,查询缓存中活动商品仅剩数量
            if (EmptyUtils.isEmpty(stringRedisService.get("限时折扣活动商品仅剩件数" + cereShopDiscount.getShopDiscountId() + sku.getSkuId()))) {
                //如果没有,取数据库仅剩件数
                surplusNumber = cereShopDiscountDetailService.findNumber(cereShopDiscount.getShopDiscountId(), sku.getSkuId());
            } else {
                //如果有,取缓存
                surplusNumber = (int) stringRedisService.get("限时折扣活动商品仅剩件数" + cereShopDiscount.getShopDiscountId() + sku.getSkuId());
            }
            //判断数量是否大于当前购买数量
            if (number > surplusNumber) {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_ALREADY_SELL_OUT, redissonLock);
            }
            //设置更新限量库存数据
            CereShopDiscountDetail detail = new CereShopDiscountDetail();
            detail.setShopDiscountId(cereShopDiscount.getShopDiscountId());
            detail.setSkuId(sku.getSkuId());
            detail.setNumber(surplusNumber - number);
            discountDetails.add(detail);
        }
        //解锁
        redissonLock.unlock();
    }

    private List<ProductCoupon> setCoupons(Integer ifAdd, CartSku sku, CereBuyerUser user) {
        if (IntegerEnum.YES.getCode().equals(ifAdd)) {
            //如果优惠券允许叠加,首先查询平台优惠券
            List<ProductCoupon> tools = new ArrayList<>();
            //根据商品id、商品价格查询满足条件的优惠券
            List<ProductCoupon> productCoupons = cereBuyerCouponService.findCouponByProduct(sku.getTotal(),
                    user.getBuyerUserId(), sku.getProductId());
            //拼接活动id、满减金额字符串以便去重
            if (!EmptyUtils.isEmpty(productCoupons)) {
                productCoupons.forEach(coupon -> {
                    coupon.setDistinct(coupon.getActivityId() + "-" + coupon.getFullMoney());
                    tools.add(coupon);
                });
            }
            //然后查询店铺优惠券
            List<ProductCoupon> shopCoupons = cereBuyerShopCouponService.findCouponByProduct(sku.getTotal(),
                    user.getBuyerUserId(), sku.getProductId());
            if (!EmptyUtils.isEmpty(tools)) {
                if (!EmptyUtils.isEmpty(shopCoupons)) {
                    List<ProductCoupon> coupons = new ArrayList<>();
                    tools.forEach(tool -> {
                        coupons.add(tool);
                    });
                    shopCoupons.forEach(shopCoupon -> {
                        coupons.add(shopCoupon);
                    });
                    return coupons;
                } else {
                    return tools;
                }
            } else {
                return shopCoupons;
            }
        }
        return null;
    }

    @Override
    public Distribution setLogisticPrice(List<CereOrderLogistics> logistics, List<CartSku> skus, CereBuyerReceive receive,
                                         Map<Long, Integer> map) {
        Distribution tribution = new Distribution();
        tribution.setDistributionPrice(new BigDecimal(0));
        //过滤不需要物流的商品
        List<CartSku> cartSkus = skus.stream().filter(sku -> IntegerEnum.YES.getCode().equals(sku.getIfLogistics()))
                .collect(Collectors.toList());
        if (EmptyUtils.isEmpty(cartSkus)) {
            tribution.setDistributionName("全国包邮");
            return tribution;
        }
        List<Distribution> distributions = new ArrayList<>();
        if (!EmptyUtils.isEmpty(logistics) && receive != null) {
            logistics.forEach(a -> {
                Distribution distribution = new Distribution();
                distribution.setDistributionName("全国包邮");
                distribution.setDistributionPrice(new BigDecimal(0));
                distribution.setLogisticsId(a.getLogisticsId());
                if (ParamEnum.CHARGE_TYPE.getCode().equals(a.getChargeType())) {
                    //如果是全国包邮
                    distribution.setDistributionName("全国包邮");
                } else if (ParamEnum.CHARGE_TYPE_NUMBER.getCode().equals(a.getChargeType())) {
                    //如果是按件,查询所有计费明细
                    List<CereLogisticsCharge> charges = cereOrderLogisticsService.findCharges(a.getLogisticsId());
                    if (!EmptyUtils.isEmpty(charges)) {
                        //遍历计费明细计算物流费用
                        charges.forEach(charge -> {
                            //校验城市匹配
                            boolean flag = matching(charge, receive);
                            if (flag) {
                                //匹配上了,计算物流费用
                                if (!EmptyUtils.isEmpty(charge.getWeight()) && !EmptyUtils.isEmpty(charge.getPrice())) {
                                    //先遍历商品数据拿到总件数
                                    BigDecimal number = new BigDecimal(0);
                                    for (CartSku cartSku : cartSkus) {
                                        number = number.add(new BigDecimal(map.get(cartSku.getSkuId())));
                                    }
                                    //商品总件数-首件
                                    BigDecimal subtract = number.subtract(charge.getWeight());
                                    //加入首件价格
                                    distribution.setDistributionPrice(distribution.getDistributionPrice().add(charge.getPrice()));
                                    if (subtract.compareTo(new BigDecimal(0)) == 1) {
                                        //如果还有剩余
                                        if (!EmptyUtils.isEmpty(charge.getSecondWeight()) && !EmptyUtils.isEmpty(charge.getSecondPrice())) {
                                            //剩余件数/续件数（向上取整）*续件价格
                                            distribution.setDistributionPrice(distribution.getDistributionPrice().
                                                    add(subtract.divide(charge.getSecondWeight(), BigDecimal.ROUND_UP).multiply(charge.getSecondPrice())));
                                        }
                                    }
                                }
                            }
                        });
                    }
                    if (distribution.getDistributionPrice().compareTo(new BigDecimal(0)) != 0) {
                        distribution.setDistributionName("按件");
                    }
                } else if (ParamEnum.CHARGE_TYPE_WEIGHT.getCode().equals(a.getChargeType())) {
                    //如果是按重量,查询所有计费明细
                    List<CereLogisticsCharge> charges = cereOrderLogisticsService.findCharges(a.getLogisticsId());
                    if (!EmptyUtils.isEmpty(charges)) {
                        charges.forEach(charge -> {
                            //校验城市匹配
                            boolean flag = matching(charge, receive);
                            if (flag) {
                                //匹配上了,计算运费
                                if (!EmptyUtils.isEmpty(charge.getWeight()) && !EmptyUtils.isEmpty(charge.getPrice())) {
                                    //先遍历商品数据拿到总重量
                                    BigDecimal weight = new BigDecimal(0);
                                    for (CartSku cartSku : cartSkus) {
                                        weight = weight.add(cartSku.getWeight());
                                    }
                                    //商品总重量-首重
                                    BigDecimal subtract = weight.subtract(charge.getWeight());
                                    //加上首重价格
                                    distribution.setDistributionPrice(distribution.getDistributionPrice().add(charge.getPrice()));
                                    if (subtract.compareTo(new BigDecimal(0)) == 1) {
                                        //如果还有剩余
                                        if (!EmptyUtils.isEmpty(charge.getSecondWeight()) && !EmptyUtils.isEmpty(charge.getSecondPrice())) {
                                            //剩余重量/续重（向上取整）*续件价格
                                            distribution.setDistributionPrice(distribution.getDistributionPrice().
                                                    add(subtract.divide(charge.getSecondWeight(), BigDecimal.ROUND_UP).multiply(charge.getSecondPrice())));
                                        }
                                    }
                                }
                            }
                        });
                    }
                    if (distribution.getDistributionPrice().compareTo(new BigDecimal(0)) != 0) {
                        distribution.setDistributionName("按重量");
                    }
                }
                if (!EmptyUtils.isEmpty(distributions)) {
                    //比较2个运费的大小,取大的放入list
                    BigDecimal decimal = distributions.get(0).getDistributionPrice();
                    if (distribution.getDistributionPrice().compareTo(decimal) == 1) {
                        distributions.clear();
                        distributions.add(distribution);
                    }
                } else {
                    distributions.add(distribution);
                }
            });
        }
        if (!EmptyUtils.isEmpty(distributions)) {
            return distributions.get(0);
        }
        return tribution;
    }

    private boolean matching(CereLogisticsCharge charge, CereBuyerReceive receive) {
        List<String> provinces = new ArrayList<>();
        List<String> cities = new ArrayList<>();
        //校验与当前收货地址城市是否匹配
        if (charge.getRegion().contains(";")) {
            //包含多个省,截取出所有的省
            String[] split = charge.getRegion().split(";");
            for (String str : split) {
                setProvinceCities(str, provinces, cities);
            }
        } else {
            //只有一个省的数据
            setProvinceCities(charge.getRegion(), provinces, cities);
        }
        //校验当前收货地址中的省份
        boolean flag = checkProvince(receive, provinces);
        if (!flag) {
            //校验收货地址中的市
            flag = checkCities(receive, cities);
        } else {
            return flag;
        }
        return false;
    }

    private boolean checkCities(CereBuyerReceive receive, List<String> cities) {
        String[] split = receive.getReceiveAdress().split("-");
        if (!EmptyUtils.isEmpty(split) && !EmptyUtils.isEmpty(cities)) {
            if (cities.contains(split[1])) {
                return true;
            }
        }
        return false;
    }

    private boolean checkProvince(CereBuyerReceive receive, List<String> provinces) {
        if (receive.getReceiveAdress().contains("-")) {
            String[] split = receive.getReceiveAdress().split("-");
            if (!EmptyUtils.isEmpty(split) && !EmptyUtils.isEmpty(provinces)) {
                if (provinces.contains(split[0])) {
                    return true;
                }
            }
        }
        return false;
    }

    private void setProvinceCities(String str, List<String> provinces, List<String> cities) {
        if (str.contains(":")) {
            //带市的数据
            String[] split1 = str.split(":");
            provinces.add(split1[0]);
            if (split1[1].contains(",")) {
                //包含多个市
                String[] split2 = split1[1].split(",");
                for (String city : split2) {
                    cities.add(city);
                }
            } else {
                //一个市
                cities.add(split1[1]);
            }
        } else {
            //不带市
            provinces.add(str);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void pay(PayParam param) throws CoBusinessException, Exception {
        String time = TimeUtils.yyMMddHHmmss();
        List<CereShopOrder> list = null;
        if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(param.getType())) {
            //父订单支付,查询所有子订单数据
            list = cereShopOrderDAO.findByParentId(param.getOrderId());
        } else {
            //子订单支付
            list = cereShopOrderDAO.findByOrderId(param.getOrderId());
        }
        //支付业务处理
        if (!EmptyUtils.isEmpty(list)) {
            List<CereDistributionOrder> distributionOrders = new ArrayList<>();
            List<CereShopConversion> conversions = new ArrayList<>();
            for (CereShopOrder order : list) {
                if (!EmptyUtils.isEmpty(order.getShopGroupWorkId())) {
                    //拼单支付业务处理
                    handleGroupWork(order, RandomStringUtil.getRandomCode(15, 0),
                            order.getOrderFormid() + "-" + RandomStringUtil.getRandomCode(4, 0) + "XCX", time);
                } else if (!EmptyUtils.isEmpty(order.getShopSeckillId())) {
                    //秒杀活动支付业务处理
                    handleSeckill(order, RandomStringUtil.getRandomCode(15, 0),
                            order.getOrderFormid() + "-" + RandomStringUtil.getRandomCode(4, 0) + "XCX", time);
                } else if (!EmptyUtils.isEmpty(order.getShopDiscountId())) {
                    //限时折扣活动支付业务处理
                    handleDiscount(order, RandomStringUtil.getRandomCode(15, 0),
                            order.getOrderFormid() + "-" + RandomStringUtil.getRandomCode(4, 0) + "XCX", time);
                } else {
                    //正常下单业务处理
                    handleOrder(order, RandomStringUtil.getRandomCode(15, 0),
                            order.getOrderFormid() + "-" + RandomStringUtil.getRandomCode(4, 0) + "XCX", time, distributionOrders, conversions);
                }
            }
            if (!EmptyUtils.isEmpty(distributionOrders)) {
                //批量插入分销订单数据
                cereDistributionOrderService.insertBatch(distributionOrders);
            }
            if (!EmptyUtils.isEmpty(conversions)) {
                //批量插入转化数据
                cereShopConversionService.insertBatch(conversions);
            }
        }
    }

    @Override
    public PayUrl getUrl(OrderGetByIdParam param, CereBuyerUser user, String ip) throws CoBusinessException, Exception {
        PayUrl payUrl = new PayUrl();
        //根据订单id查询支付金额数据
        CereShopOrder shopOrder = cereShopOrderDAO.findById(param.getOrderId());
        if (shopOrder != null) {
            payUrl.setOrderId(param.getOrderId());
            payUrl.setMoney(shopOrder.getPrice());
            //生成收款码
            String formid = shopOrder.getOrderFormid() + "-" + RandomStringUtil.getRandomCode(3, 0) + "XCX";
            String code_url = wxPayService.getOrderCollectionCode(formid, shopOrder.getPrice(),
                    ip, WxPayEnum.PAY_TYPE_NATIVE.getCode());
            if (!EmptyUtils.isEmpty(code_url)) {
                //生成收款二维码图片
                Map<EncodeHintType, Object> hints = new HashMap<>();
                // 设置纠错等级
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
                // 编码类型
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, 400, 400, hints);
                MatrixToImageConfig config = new MatrixToImageConfig();
                BufferedImage image = toBufferedImage(bitMatrix, config);
                //上传图片到OSS
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(image, "png", out);
                byte[] bytes = out.toByteArray();
                String url = uploadService.uploadByte(formid + ".png", bytes);
                payUrl.setUrl(url);
            }
        }
        return payUrl;
    }

    @Override
    public PayUrl checkPay(PayParam param) throws CoBusinessException {
        PayUrl payUrl = new PayUrl();
        List<CereShopOrder> list = null;
        //查询订单是否支付成功
        if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(param.getType())) {
            //父订单校验
            list = cereShopOrderDAO.checkPayParent(param.getOrderId());
        } else {
            //子订单校验
            list = cereShopOrderDAO.checkPayOrder(param.getOrderId());
        }
        if (!EmptyUtils.isEmpty(list)) {
            payUrl.setCode(StringEnum.WX_PAY_SUCCESS.getCode());
        }
        return payUrl;
    }

    @Override
    public List<CartSku> refund(OrderGetByIdParam param, CereBuyerUser user) throws CoBusinessException {
        List<CartSku> skus = null;
        //查询当前订单已经提交过的售后商品规格id数组
        List<Long> ids = cereShopOrderDAO.findAfterSkuIdsByOrderId(param.getOrderId());
        if (EmptyUtils.isEmpty(ids)) {
            //未申请过售后或者售后失败等,查询订单所有商品列表返回
            skus = cereProductSkuService.findSkuByOrderId(param.getOrderId());
        } else {
            //有售后商品,查询当前订单除了这些商品以外的其他商品
            skus = cereProductSkuService.findSkuByIds(ids, param.getOrderId());
        }
        for (CartSku c : skus) {
            c.setShelveState(cereShopProductService.getsheStateByid(c.getProductId()));
        }
        return skus;
    }


    public String StringToDate(String sdate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date date = null;
        try {
            date = simpleDateFormat.parse(sdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        System.out.println(simpleDateFormat.format(date));
        return simpleDateFormat.format(date);
    }


}
